_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7 values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
ab36788dcc58cdf11434a24f5f99135a88ebf70e65193ba5cb9df93241bd6fbd | bmeurer/ocamljit2 | tata.mli | (* a comment *)
val tata : string
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/ocamlbuild/test/test2/tata.mli | ocaml | a comment | val tata : string
|
0baa009cef6f694ecc6aecffd721a73b79ad5e12dabd6e9f9d2b899b0da6cdb7 | rasheedja/PropaFP | Smt.hs | # LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
# LANGUAGE LambdaCase #
module PropaFP.Parsers.Smt where
import MixedTypesNumPrelude hiding (unzip)
import qualified Prelude as P
import System.IO.Unsafe
import PropaFP.Expression
import qualified PropaFP.Parsers.Lisp.Parser as LP
import qualified PropaFP.Parsers.Lisp.DataTypes as LD
import Data.Char (digitToInt)
import Data.Word
import qualified Data.ByteString.Lazy as B
import Data.Binary.Get
import Data.Maybe (mapMaybe)
import PropaFP.VarMap
import PropaFP.DeriveBounds
import PropaFP.EliminateFloats
import PropaFP.Eliminator (minMaxAbsEliminatorECNF, minMaxAbsEliminator)
import Data.List (nub, sort, isPrefixOf, sortBy, partition, foldl')
import Data.List.NonEmpty (unzip)
import Control.Arrow ((&&&))
import Debug.Trace
import PropaFP.Translators.DReal (formulaAndVarMapToDReal)
import Text.Regex.TDFA ( (=~) )
import Data.Ratio
import PropaFP.DeriveBounds
import qualified Data.Map as M
import AERN2.MP (endpoints, mpBallP, prec)
data ParsingMode = Why3 | CNF
parser :: String -> [LD.Expression]
parser = LP.analyzeExpressionSequence . LP.parseSequence . LP.tokenize
parseSMT2 :: FilePath -> IO [LD.Expression]
parseSMT2 filePath = fmap parser $ P.readFile filePath
-- |Find assertions in a parsed expression
-- Assertions are Application types with the operator being a Variable equal to "assert"
-- Assertions only have one 'operands'
findAssertions :: [LD.Expression] -> [LD.Expression]
findAssertions [] = []
findAssertions [ LD.Application ( LD.Variable " assert " ) [ operands ] ] = [ operands ]
findAssertions ((LD.Application (LD.Variable "assert") [operands]) : expressions) = operands : findAssertions expressions
-- findAssertions ((LD.Application (LD.Variable var) [operands]) : expressions) = operands : findAssertions expressions
findAssertions (e : expressions) = findAssertions expressions
findFunctionInputsAndOutputs :: [LD.Expression] -> [(String, ([String], String))]
findFunctionInputsAndOutputs [] = []
findFunctionInputsAndOutputs ((LD.Application (LD.Variable "declare-fun") [LD.Variable fName, fInputsAsExpressions, LD.Variable fOutputs]) : expressions) =
(fName, (expressionInputsAsString fInputsAsExpressions, fOutputs)) : findFunctionInputsAndOutputs expressions
where
expressionInputsAsString :: LD.Expression -> [String]
expressionInputsAsString (LD.Application (LD.Variable inputTypeAsString) remainingInputsAsExpression) = inputTypeAsString : concatMap expressionInputsAsString remainingInputsAsExpression
expressionInputsAsString (LD.Variable inputTypeAsString) = [inputTypeAsString]
expressionInputsAsString _ = []
findFunctionInputsAndOutputs (_ : expressions) = findFunctionInputsAndOutputs expressions
-- |Find function declarations in a parsed expression
-- Function declarations are Application types with the operator being a Variable equal to "declare-fun"
Function declarations contain 3 operands
-- - Operand 1 is the name of the function
-- - Operand 2 is an Application type which can be thought of as the parameters of the functions
If the function has no paramters , this operand is LD.Null
-- - Operand 3 is the type of the function
findDeclarations :: [LD.Expression] -> [LD.Expression]
findDeclarations [] = []
findDeclarations (declaration@(LD.Application (LD.Variable "declare-fun") _) : expressions) = declaration : findDeclarations expressions
findDeclarations (_ : expressions) = findDeclarations expressions
findVariables :: [LD.Expression] -> [(String, String)]
findVariables [] = []
findVariables (LD.Application (LD.Variable "declare-const") [LD.Variable varName, LD.Variable varType] : expressions)
= (varName, varType) : findVariables expressions
findVariables (LD.Application (LD.Variable "declare-fun") [LD.Variable varName, LD.Null, LD.Variable varType] : expressions)
= (varName, varType) : findVariables expressions
findVariables (_ : expressions) = findVariables expressions
findIntegerVariables :: [(String, String)] -> [(String, VarType)]
findIntegerVariables [] = []
findIntegerVariables ((v,t) : vs) =
if "Int" `isPrefixOf` t || "int" `isPrefixOf` t
then (v, Integer) : findIntegerVariables vs
else findIntegerVariables vs
-- |Finds goals in assertion operands
-- Goals are S-Expressions with a top level 'not'
findGoalsInAssertions :: [LD.Expression] -> [LD.Expression]
findGoalsInAssertions [] = []
findGoalsInAssertions ((LD.Application (LD.Variable operator) operands) : assertions) =
if operator == "not"
Take head of operands since not has only one operand
else findGoalsInAssertions assertions
findGoalsInAssertions (_ : assertions) = findGoalsInAssertions assertions
-- |Takes the last element from a list of assertions
-- We assume that the last element is the goal
takeGoalFromAssertions :: [LD.Expression] -> (LD.Expression, [LD.Expression])
takeGoalFromAssertions asserts = (goal, assertsWithoutGoal)
where
numberOfAssertions = length asserts
goal = last asserts -- FIXME: Unsafe. If asserts is empty, this will fail
assertsWithoutGoal = take (numberOfAssertions - 1) asserts
-- safelyTypeExpression :: String -> [(String, ([String], String))] -> E -> E
safelyTypeExpression smtFunction functionsWithInputsAndOutputs exactExpression =
case lookup smtFunction functionsWithInputsAndOutputs of
-- Just (inputs, output)
|Attempts to parse FComp Ops , i.e. parse bool_eq to Just ( )
parseFCompOp :: String -> Maybe (E -> E -> F)
parseFCompOp operator =
case operator of
n
| n `elem` [">=", "fp.geq", "oge", "oge__logic"] || (n =~ "^bool_ge$|^bool_ge[0-9]+$" :: Bool) -> Just $ FComp Ge
| n `elem` [">", "fp.gt", "ogt", "ogt__logic"] || (n =~ "^bool_gt$|^bool_gt[0-9]+$" :: Bool) -> Just $ FComp Gt
| n `elem` ["<=", "fp.leq", "ole", "ole__logic"] || (n =~ "^bool_le$|^bool_le[0-9]+$" :: Bool) -> Just $ FComp Le
| n `elem` ["<", "fp.lt", "olt", "olt__logic"] || (n =~ "^bool_lt$|^bool_lt[0-9]+$" :: Bool) -> Just $ FComp Lt
| n `elem` ["=", "fp.eq"] || (n =~ "^bool_eq$|^bool_eq[0-9]+$|^user_eq$|^user_eq[0-9]+$" :: Bool) -> Just $ FComp Eq
| "bool_neq" `isPrefixOf` n -> Just $ \e1 e2 -> FNot (FComp Eq e1 e2)
_ -> Nothing
-- parseIte :: LD.Expression -> LD.Expression -> LD.Expression -> Maybe F
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs Nothing =
case termToF cond functionsWithInputsAndOutputs of
Just condF ->
case (termToF thenTerm functionsWithInputsAndOutputs, termToF elseTerm functionsWithInputsAndOutputs) of
(Just thenTermF, Just elseTermF) ->
Just $ FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) elseTermF)
(_, _) -> Nothing
Nothing -> Nothing
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just compTerm) =
case termToF cond functionsWithInputsAndOutputs of
(Just condF) ->
case (termToE thenTerm functionsWithInputsAndOutputs, termToE elseTerm functionsWithInputsAndOutputs) of
(Just thenTermE, Just elseTermE) ->
Just $ FConn And
(FConn Impl condF (compTerm thenTermE))
(FConn Impl (FNot condF) (compTerm elseTermE))
(Just thenTermE, _) ->
case elseTerm of
LD.Application (LD.Variable "ite") [elseCond, elseThenTerm, elseElseTerm] ->
case parseIte elseCond elseThenTerm elseElseTerm functionsWithInputsAndOutputs (Just compTerm) of
Just elseTermF -> Just $
FConn And
(FConn Impl condF (compTerm thenTermE))
(FConn Impl (FNot condF) elseTermF)
_ -> Nothing
_ -> Nothing
(_, Just elseTermE) ->
case thenTerm of
LD.Application (LD.Variable "ite") [thenCond, thenThenTerm, thenElseTerm] ->
case parseIte thenCond thenThenTerm thenElseTerm functionsWithInputsAndOutputs (Just compTerm) of
Just thenTermF -> Just $
FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) (compTerm elseTermE))
_ -> Nothing
_ -> Nothing
(_, _) ->
case (thenTerm, elseTerm) of
(LD.Application (LD.Variable "ite") [thenCond, thenThenTerm, thenElseTerm], LD.Application (LD.Variable "ite") [elseCond, elseThenTerm, elseElseTerm]) ->
case (parseIte thenCond thenThenTerm thenElseTerm functionsWithInputsAndOutputs (Just compTerm), parseIte elseCond elseThenTerm elseElseTerm functionsWithInputsAndOutputs (Just compTerm)) of
(Just thenTermF, Just elseTermF) -> Just $
FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) elseTermF)
(_, _) -> Nothing
(_, _) -> Nothing
Nothing -> Nothing
termToF :: LD.Expression -> [(String, ([String], String))] -> Maybe F
termToF (LD.Application (LD.Variable operator) [op]) functionsWithInputsAndOutputs = -- Single param operators
case termToE op functionsWithInputsAndOutputs of -- Ops with E params
Just e ->
case operator of
"fp.isFinite32" ->
let maxFloat = (2.0 - (1/(2^23))) * (2^127)
minFloat = negate maxFloat
in
Just $ FConn And (FComp Le (Lit minFloat) e) (FComp Le e (Lit maxFloat))
"fp.isFinite64" ->
let maxFloat = (2.0 - (1/(2^52))) * (2^1023)
minFloat = negate maxFloat
in
Just $ FConn And (FComp Le (Lit minFloat) e) (FComp Le e (Lit maxFloat))
_ -> Nothing
Nothing ->
case termToF op functionsWithInputsAndOutputs of
Just f ->
case operator of
"not" -> Just $ FNot f
_ -> Nothing
_ -> Nothing
Two param operations
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
case parseFCompOp operator of
Just fCompOp -> Just $ fCompOp e1 e2
_ -> Nothing
(_, _) ->
case (termToF op1 functionsWithInputsAndOutputs, termToF op2 functionsWithInputsAndOutputs) of
(Just f1, Just f2) ->
case operator of
"and" -> Just $ FConn And f1 f2
"or" -> Just $ FConn Or f1 f2
"=>" -> Just $ FConn Impl f1 f2
"=" -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
n
| "bool_eq" `isPrefixOf` n -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
| "bool_neq" `isPrefixOf` n -> Just $ FNot $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
| "user_eq" `isPrefixOf` n -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
_ -> Nothing
where it is used as an expression
(_, _) ->
case (op1, termToE op2 functionsWithInputsAndOutputs) of
(LD.Application (LD.Variable "ite") [cond, thenTerm, elseTerm], Just e2) ->
case parseFCompOp operator of
Just fCompOp -> parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just (\e -> fCompOp e e2))
Nothing -> Nothing
(_, _) ->
case (termToE op1 functionsWithInputsAndOutputs, op2) of
(Just e1, LD.Application (LD.Variable "ite") [cond, thenTerm, elseTerm]) ->
case parseFCompOp operator of
Just fCompOp -> parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just (\e -> fCompOp e1 e))
Nothing -> Nothing
(_, _) -> Nothing
termToF (LD.Application (LD.Variable "ite") [cond, thenTerm, elseTerm]) functionsWithInputsAndOutputs = -- if-then-else operator with F types
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs Nothing
termToF (LD.Variable "true") functionsWithInputsAndOutputs = Just FTrue
termToF (LD.Variable "false") functionsWithInputsAndOutputs = Just FFalse
termToF _ _ = Nothing
termToE :: LD.Expression -> [(String, ([String], String))] -> Maybe E
Parse 4 * atan(1 ) as Pi ( used by our dReal SMT translator )
termToE (LD.Application (LD.Variable "*") [LD.Number 4, LD.Application (LD.Variable "atan") [LD.Number 1]]) functionsWithInputsAndOutputs = Just $ Pi
-- Symbols/Literals
termToE (LD.Variable "true") functionsWithInputsAndOutputs = Nothing -- These should be parsed to F
termToE (LD.Variable "false") functionsWithInputsAndOutputs = Nothing -- These should be parsed to F
termToE (LD.Variable var) functionsWithInputsAndOutputs = Just $ Var var
termToE (LD.Number num) functionsWithInputsAndOutputs = Just $ Lit num
one param PropaFP translator functions
-- RoundToInt
termToE (LD.Application (LD.Variable "to_int_rne") [p]) functionsWithInputsAndOutputs = RoundToInteger RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtp") [p]) functionsWithInputsAndOutputs = RoundToInteger RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtn") [p]) functionsWithInputsAndOutputs = RoundToInteger RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtz") [p]) functionsWithInputsAndOutputs = RoundToInteger RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rna") [p]) functionsWithInputsAndOutputs = RoundToInteger RNA <$> termToE p functionsWithInputsAndOutputs
Float32
termToE (LD.Application (LD.Variable "float32_rne") [p]) functionsWithInputsAndOutputs = Float32 RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtp") [p]) functionsWithInputsAndOutputs = Float32 RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtn") [p]) functionsWithInputsAndOutputs = Float32 RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtz") [p]) functionsWithInputsAndOutputs = Float32 RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rna") [p]) functionsWithInputsAndOutputs = Float32 RNA <$> termToE p functionsWithInputsAndOutputs
Float64
termToE (LD.Application (LD.Variable "float64_rne") [p]) functionsWithInputsAndOutputs = Float64 RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtp") [p]) functionsWithInputsAndOutputs = Float64 RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtn") [p]) functionsWithInputsAndOutputs = Float64 RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtz") [p]) functionsWithInputsAndOutputs = Float64 RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rna") [p]) functionsWithInputsAndOutputs = Float64 RNA <$> termToE p functionsWithInputsAndOutputs
one param functions
termToE (LD.Application (LD.Variable operator) [op]) functionsWithInputsAndOutputs =
case termToE op functionsWithInputsAndOutputs of
Nothing -> Nothing
Just e -> case operator of
n
| (n =~ "^real_pi$|^real_pi[0-9]+$" :: Bool) -> Just Pi
| (n =~ "^abs$|^abs[0-9]+$" :: Bool) -> Just $ EUnOp Abs e
| (n =~ "^sin$|^sin[0-9]+$|^real_sin$|^real_sin[0-9]+$" :: Bool) -> Just $ EUnOp Sin e
| (n =~ "^cos$|^cos[0-9]+$|^real_cos$|^real_cos[0-9]+$" :: Bool) -> Just $ EUnOp Cos e
| (n =~ "^sqrt$|^sqrt[0-9]+$|^real_square_root$|^real_square_root[0-9]+$" :: Bool) -> Just $ EUnOp Sqrt e
| (n =~ "^fp.to_real$|^fp.to_real[0-9]+$|^to_real$|^to_real[0-9]+$" :: Bool) -> Just e
"-" -> Just $ EUnOp Negate e
SPARK Reals functions
"from_int" -> Just e
Some to_int functions . different suffixes ( 1 , 2 , etc . )
e.g. In one file , to_int1 : : Float - > Int
to_int2 : : Int
-- Are these suffixes consistent?
-- Float functions
"fp.abs" -> Just $ EUnOp Abs e
"fp.neg" -> Just $ EUnOp Negate e
-- "fp.to_real" -> Just e
-- "to_real" -> Just e
-- "value" -> Just e
-- Undefined functions
"fp.isNormal" -> Nothing
"fp.isSubnormal" -> Nothing
"fp.isZero" -> Nothing
"fp.isNaN" -> Nothing
"fp.isPositive" -> Nothing
"fp.isNegative" -> Nothing
"fp.isIntegral32" -> Nothing
"fp.isIntegral64" -> Nothing
_ -> Nothing
where
deriveTypeForOneArgFunctions :: String -> (E -> E) -> E -> Maybe E
deriveTypeForOneArgFunctions functionName functionAsExpression functionArg =
-- case lookup functionName functionsWithInputsAndOutputs of
-- Just ([inputType], outputType) ->
let
(mInputTypes, mOutputType) = unzip $ lookup functionName functionsWithInputsAndOutputs
-- case lookup functionName functionsWithInputsAndOutputs of
Just ( inputTypes , outputType ) - > ( Just inputTypes , Just outputType )
-- Nothing -> (Nothing, Nothing)
newFunctionArg = functionArg
-- case mInputTypes of
-- Just [inputType] ->
-- case inputType of
-- " Float32 " - > Float32 RNE functionArg
-- -- "Float64" -> Float64 RNE functionArg
_ - > functionArg -- Do not deal with multiple param args for one param functions . TODO : Check if these can occur , i.e. something like RoundingMode Float32
mNewFunctionAsExpression =
case mOutputType of
Just outputType ->
case outputType of
" Float32 " - > Float32 RNE . functionAsExpression -- TODO : Make these Nothing if we ca n't deal with them
" Float64 " - > . functionAsExpression -- TODO : Make these Nothing if we ca n't deal with them
"Real" -> Just functionAsExpression --FIXME: Should match on other possible names. Real/real Int/int/integer, etc. I've only seen these alt names in function definitions/axioms, not assertions, but would still be more safe.
"Int" -> Just functionAsExpression -- FIXME: Round here?
_ -> Nothing -- These should be floats, which we cannot deal with for now
Nothing -> Just functionAsExpression -- No type given, assume real
in
case mNewFunctionAsExpression of
Just newFunctionAsExpression -> Just $ newFunctionAsExpression newFunctionArg
Nothing -> Nothing
-- Nothing -> functionAsExpression functionArg
two param PropaFP translator functions
termToE (LD.Application (LD.Variable "min") [p1, p2]) functionsWithInputsAndOutputs = EBinOp Min <$> termToE p1 functionsWithInputsAndOutputs <*> termToE p2 functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "max") [p1, p2]) functionsWithInputsAndOutputs = EBinOp Max <$> termToE p1 functionsWithInputsAndOutputs <*> termToE p2 functionsWithInputsAndOutputs
two param functions
params are either two different E types , or one param is a rounding mode and another is the arg
termToE (LD.Application (LD.Variable operator) [op1, op2]) functionsWithInputsAndOutputs =
case (parseRoundingMode op1, termToE op2 functionsWithInputsAndOutputs) of
(Just roundingMode, Just e) ->
case operator of
n
| (n =~ "^round$|^round[0-9]+$" :: Bool) -> Just $ Float roundingMode e --FIXME: remove this? not used with cvc4 driver?
| (n =~ "^to_int$|^to_int[0-9]+$" :: Bool) -> Just $ RoundToInteger roundingMode e
| (n =~ "^of_int$|^of_int[0-9]+$" :: Bool) ->
case lookup n functionsWithInputsAndOutputs of
Just (_, outputType) ->
case outputType of
o -- Why3 will type check that the input is an integer, making these safe
| o `elem` ["Float32", "single"] -> Just $ Float32 roundingMode e
| o `elem` ["Float64", "double"] -> Just $ Float64 roundingMode e
| o `elem` ["Real", "real"] -> Just e
_ -> Nothing
_ -> Nothing
"fp.roundToIntegral" -> Just $ RoundToInteger roundingMode e
_ -> Nothing
_ ->
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
case operator of
n
" o ... " functions are from SPARK Reals
| n `elem` ["+", "oadd", "oadd__logic"] -> Just $ EBinOp Add e1 e2
| n `elem` ["-", "osubtract", "osubtract__logic"] -> Just $ EBinOp Sub e1 e2
| n `elem` ["*", "omultiply", "omultiply__logic"] -> Just $ EBinOp Mul e1 e2
| n `elem` ["/", "odivide", "odivide__logic"] -> Just $ EBinOp Div e1 e2
| (n =~ "^pow$|^pow[0-9]+$|^power$|^power[0-9]+$" :: Bool) -> Just $ EBinOp Pow e1 e2 --FIXME: remove int pow? only use int pow if actually specified?
| n == "^" -> Just $ EBinOp Pow e1 e2
case lookup n functionsWithInputsAndOutputs of
Just ( [ " Real " , " Real " ] , " Real " ) - > Just $ EBinOp Pow e1 e2
-- Just ([input1, "Int"], output) ->
-- let
-- mExactPowExpression =
if input1 = = " Int " || input1 = = " Real "
-- then case e2 of
Lit l2 - > if denominator l2 = = 1.0 then Just $ PowI e1 ( numerator l2 ) else Just $ EBinOp Pow e1 e2
_ - > Just $ EBinOp Pow e1 e2
-- else Nothing
-- in case mExactPowExpression of
-- Just exactPowExpression -> case output of
-- "Real" -> Just exactPowExpression
-- "Int" -> Just $ RoundToInteger RNE exactPowExpression
-- _ -> Nothing
-- Nothing -> Nothing
-- Nothing -> -- No input/output, treat as real pow
-- case e2 of
Lit l2 - > if denominator l2 = = 1.0 then Just $ PowI e1 ( numerator l2 ) else Just $ EBinOp Pow e1 e2
_ - > Just $ EBinOp Pow e1 e2
-- _ -> Nothing
| (n =~ "^mod$|^mod[0-9]+$" :: Bool) -> Just $ EBinOp Mod e1 e2
case lookup n functionsWithInputsAndOutputs of
Just ( [ " Real " , " Real " ] , " Real " ) - > Just $ EBinOp Mod e1 e2
Just ( [ " Int " , " Int " ] , " Int " ) - > Just $ RoundToInteger RNE $ EBinOp Mod e1 e2 --TODO : might be worth implementing
-- -- No input/output, treat as real mod
-- Nothing -> Just $ EBinOp Mod e1 e2
-- _ -> Nothing
_ -> Nothing
(_, _) -> Nothing
-- Float bits to Rational
termToE (LD.Application (LD.Variable "fp") [LD.Variable sSign, LD.Variable sExponent, LD.Variable sMantissa]) functionsWithInputsAndOutputs =
let
bSign = drop 2 sSign
bExponent = drop 2 sExponent
bMantissa = drop 2 sMantissa
bFull = bSign ++ bExponent ++ bMantissa
Read a string of ( ' 1 ' or ' 0 ' ) where the first digit is the most significant
The digit parameter denotes the current digit , should be equal to length of the first param at all times
readBits :: String -> Integer -> Integer
readBits [] _ = 0
readBits (bit : bits) digit = digitToInt bit * (2 ^ (digit - 1)) + readBits bits (digit - 1)
bitsToWord8 :: String -> [Word8]
bitsToWord8 bits =
let wordS = take 8 bits
rem = drop 8 bits
wordV = readBits wordS 8
in
P.fromInteger wordV : bitsToWord8 rem
bsFloat = B.pack $ bitsToWord8 bFull
in
if all (`elem` "01") bFull
then
case length bFull of
32 -> Just $ Lit $ toRational $ runGet getFloatbe bsFloat
64 -> Just $ Lit $ toRational $ runGet getDoublebe bsFloat
32 - > Just $ Float32 RNE $ Lit $ toRational $ runGet getFloatbe bsFloat
64 - > Just $ Float64 RNE $ Lit $ toRational $ runGet
_ -> Nothing
else Nothing
Float functions , three params . Other three param functions should be placed before here
termToE (LD.Application (LD.Variable operator) [roundingMode, op1, op2]) functionsWithInputsAndOutputs =
-- case operator of
-- SPARK Reals
-- "fp.to_real" -> Nothing
-- _ -> -- Known ops
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
case parseRoundingMode roundingMode of -- Floating-point ops
Just mode ->
case operator of
"fp.add" -> Just $ Float mode $ EBinOp Add e1 e2
"fp.sub" -> Just $ Float mode $ EBinOp Sub e1 e2
"fp.mul" -> Just $ Float mode $ EBinOp Mul e1 e2
"fp.div" -> Just $ Float mode $ EBinOp Div e1 e2
_ -> Nothing
Nothing -> Nothing
(_, _) -> Nothing
termToE _ _ = Nothing
collapseOrs :: [LD.Expression] -> [LD.Expression]
collapseOrs = map collapseOr
collapseOr :: LD.Expression -> LD.Expression
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "<") args1, LD.Application (LD.Variable "=") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable "<=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "=") args1, LD.Application (LD.Variable "<") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable "<=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable ">") args1, LD.Application (LD.Variable "=") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable ">=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "=") args1, LD.Application (LD.Variable ">") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable ">=") args1
else orig
collapseOr (LD.Application operator args) = LD.Application operator (collapseOrs args)
collapseOr e = e
-- |Replace function guards which are known to be always true with true.
eliminateKnownFunctionGuards :: [LD.Expression] -> [LD.Expression]
eliminateKnownFunctionGuards = map eliminateKnownFunctionGuard
-- |Replace function guard which is known to be always true with true.
eliminateKnownFunctionGuard :: LD.Expression -> LD.Expression
eliminateKnownFunctionGuard orig@(LD.Application operator@(LD.Variable var) args@(guardedFunction : _)) =
let
knownGuardsRegex =
"^real_sin__function_guard$|^real_sin__function_guard[0-9]+$|" ++
"^real_cos__function_guard$|^real_cos__function_guard[0-9]+$|" ++
"^real_square_root__function_guard$|^real_square_root__function_guard[0-9]+$|" ++
"^real_pi__function_guard$|^real_pi__function_guard[0-9]+$"
in
if (var =~ knownGuardsRegex :: Bool)
then LD.Variable "true"
else LD.Application operator (eliminateKnownFunctionGuards args)
eliminateKnownFunctionGuard (LD.Application operator args) = LD.Application operator (eliminateKnownFunctionGuards args)
eliminateKnownFunctionGuard e = e
termsToF :: [LD.Expression] -> [(String, ([String], String))] -> [F]
termsToF es fs = mapMaybe (`termToF` fs) es
determineFloatTypeE :: E -> [(String, String)] -> Maybe E
determineFloatTypeE (EBinOp op e1 e2) varTypeMap = case determineFloatTypeE e1 varTypeMap of
Just p1 ->
case determineFloatTypeE e2 varTypeMap of
Just p2 -> Just $ EBinOp op p1 p2
Nothing -> Nothing
Nothing -> Nothing
determineFloatTypeE (EUnOp op e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ EUnOp op p
Nothing -> Nothing
determineFloatTypeE (PowI e i) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ PowI p i
Nothing -> Nothing
determineFloatTypeE (Float r e) varTypeMap = case mVariableType of
Just variableType ->
case variableType of
t
| t `elem` ["Float32", "single"] ->
case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float32 r p
Nothing -> Nothing
| t `elem` ["Float64", "double"] ->
case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float64 r p
Nothing -> Nothing
_ -> Nothing
Nothing -> Nothing
where
allVars = findVariablesInExpressions e
knownVarsWithPrecision = knownFloatVars e
knownVars = map fst knownVarsWithPrecision
unknownVars = filter (`notElem` knownVars) allVars
mVariableType = findVariableType unknownVars varTypeMap knownVarsWithPrecision Nothing
determineFloatTypeE (Float32 r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float32 r p
Nothing -> Nothing
determineFloatTypeE (Float64 r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float64 r p
Nothing -> Nothing
determineFloatTypeE (RoundToInteger r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ RoundToInteger r p
Nothing -> Nothing
determineFloatTypeE Pi _ = Just Pi
determineFloatTypeE (Var v) varTypeMap = case lookup v varTypeMap of
Just variableType ->
case variableType of
-- t
| t ` elem ` [ " Float32 " , " single " ] - > Just $ Float32 RNE $ Var v
| t ` elem ` [ " Float64 " , " double " ] - > Just $ Float64 RNE $ Var v
_ -> Just $ Var v -- It is safe to treat integers and rationals as reals
_ -> Just $ Var v
determineFloatTypeE (Lit n) _ = Just $ Lit n
-- |Tries to determine whether a Float operation is single or double precision
-- by searching for the type of all variables appearing in the function. If the
types match and are all either Float32 / Float64 , we can determine the type .
determineFloatTypeF :: F -> [(String, String)] -> Maybe F
determineFloatTypeF (FComp op e1 e2) varTypeMap = case (determineFloatTypeE e1 varTypeMap, determineFloatTypeE e2 varTypeMap) of
(Just p1, Just p2) -> Just $ FComp op p1 p2
(_, _) -> Nothing
determineFloatTypeF (FConn op f1 f2) varTypeMap = case (determineFloatTypeF f1 varTypeMap, determineFloatTypeF f2 varTypeMap) of
(Just p1, Just p2) -> Just $ FConn op p1 p2
(_, _) -> Nothing
determineFloatTypeF (FNot f) varTypeMap = case determineFloatTypeF f varTypeMap of
Just p -> Just $ FNot p
Nothing -> Nothing
determineFloatTypeF FTrue _ = Just FTrue
determineFloatTypeF FFalse _ = Just FFalse
-- |Find the type for the given variables
-- Type is looked for in the supplied map
-- If all found types match, return this type
findVariableType :: [String] -> [(String, String)] -> [(String, Integer)] -> Maybe String -> Maybe String
findVariableType [] _ [] mFoundType = mFoundType
findVariableType [] _ ((_, precision) : vars) mFoundType =
case mFoundType of
Just t ->
if (t `elem` ["Float32", "single"] && precision == 32) || ((t `elem` ["Float64", "double"]) && (precision == 64))
then findVariableType [] [] vars mFoundType
else Nothing
Nothing ->
case precision of
32 -> findVariableType [] [] vars (Just "Float32")
64 -> findVariableType [] [] vars (Just "Float64")
_ -> Nothing
findVariableType (v: vs) varTypeMap knownVarsWithPrecision mFoundType =
case lookup v varTypeMap of
Just t ->
if "Int" `isPrefixOf` t then
findVariableType vs varTypeMap knownVarsWithPrecision mFoundType
else
case mFoundType of
Just f -> if f == t then findVariableType vs varTypeMap knownVarsWithPrecision (Just t) else Nothing
Nothing -> findVariableType vs varTypeMap knownVarsWithPrecision (Just t)
Nothing -> Nothing
knownFloatVars :: E -> [(String, Integer)]
knownFloatVars e = removeConflictingVars . nub $ findAllFloatVars e
where
removeConflictingVars :: [(String, Integer)] -> [(String, Integer)]
removeConflictingVars [] = []
removeConflictingVars ((v, t) : vs) =
if v `elem` map fst vs
then removeConflictingVars $ filter (\(v', _) -> v /= v') vs
else (v, t) : removeConflictingVars vs
findAllFloatVars (EBinOp _ e1 e2) = knownFloatVars e1 ++ knownFloatVars e2
findAllFloatVars (EUnOp _ e) = knownFloatVars e
findAllFloatVars (PowI e _) = knownFloatVars e
findAllFloatVars (Float _ e) = knownFloatVars e
findAllFloatVars (Float32 _ (Var v)) = [(v, 32)]
findAllFloatVars (Float64 _ (Var v)) = [(v, 64)]
findAllFloatVars (Float32 _ e) = knownFloatVars e
findAllFloatVars (Float64 _ e) = knownFloatVars e
findAllFloatVars (RoundToInteger _ e) = knownFloatVars e
findAllFloatVars (Var _) = []
findAllFloatVars (Lit _) = []
findAllFloatVars Pi = []
findVariablesInFormula :: F -> [String]
findVariablesInFormula f = nub $ findVars f
where
findVars (FConn _ f1 f2) = findVars f1 ++ findVars f2
findVars (FComp _ e1 e2) = findVariablesInExpressions e1 ++ findVariablesInExpressions e2
findVars (FNot f1) = findVars f1
findVars FTrue = []
findVars FFalse = []
findVariablesInExpressions :: E -> [String]
findVariablesInExpressions (EBinOp _ e1 e2) = findVariablesInExpressions e1 ++ findVariablesInExpressions e2
findVariablesInExpressions (EUnOp _ e) = findVariablesInExpressions e
findVariablesInExpressions (PowI e _) = findVariablesInExpressions e
findVariablesInExpressions (Float _ e) = findVariablesInExpressions e
findVariablesInExpressions (Float32 _ e) = findVariablesInExpressions e
findVariablesInExpressions (Float64 _ e) = findVariablesInExpressions e
findVariablesInExpressions (RoundToInteger _ e) = findVariablesInExpressions e
findVariablesInExpressions (Var v) = [v]
findVariablesInExpressions (Lit _) = []
findVariablesInExpressions Pi = []
parseRoundingMode :: LD.Expression -> Maybe RoundingMode
parseRoundingMode (LD.Variable mode) =
case mode of
m
| m `elem` ["RNE", "NearestTiesToEven"] -> Just RNE
| m `elem` ["RTP", "Up"] -> Just RTP
| m `elem` ["RTN", "Down"] -> Just RTN
| m `elem` ["RTZ", "ToZero"] -> Just RTZ
| m `elem` ["RNA"] -> Just RNA
_ -> Nothing
parseRoundingMode _ = Nothing
-- |Process a parsed list of expressions to a VC.
--
-- If the parsing mode is Why3, everything in the context implies the goal (empty context means we only have a goal).
-- If the goal cannot be parsed, we return Nothing.
--
-- If the parsing mode is CNF, parse all assertions into a CNF. If any assertion cannot be parsed, return Nothing.
If any assertion contains , return Nothing .
processVC :: [LD.Expression] -> Maybe (F, [(String, String)])
processVC parsedExpressions =
Just (foldAssertionsF assertionsF, variablesWithTypes)
where
assertions = findAssertions parsedExpressions
assertionsF = mapMaybe (`determineFloatTypeF` variablesWithTypes) $ (termsToF . eliminateKnownFunctionGuards . collapseOrs) assertions functionsWithInputsAndOutputs
variablesWithTypes = findVariables parsedExpressions
functionsWithInputsAndOutputs = findFunctionInputsAndOutputs parsedExpressions
foldAssertionsF :: [F] -> F
foldAssertionsF [] = error "processVC - foldAssertionsF: Empty list given"
foldAssertionsF [f] = f
foldAssertionsF (f : fs) = FConn And f (foldAssertionsF fs)
-- |Looks for pi vars (vars named pi/pi{i} where {i} is some integer) and symbolic bounds.
If the bounds are better than those given to the real pi in Why3 , replace the variable with exact pi .
symbolicallySubstitutePiVars :: F -> F
symbolicallySubstitutePiVars f = substVarsWithPi piVars f
where
piVars = nub (aux f)
substVarsWithPi :: [String] -> F -> F
substVarsWithPi [] f' = f'
substVarsWithPi (v : _) f' = substVarFWithE v f' Pi
aux :: F -> [String]
aux (FConn And f1 f2) = aux f1 ++ aux f2
aux (FComp Lt (EBinOp Div (Lit numer) (Lit denom)) (Var var)) =
[var |
-- If variable is pi or pi# where # is a number
(var =~ "^pi$|^pi[0-9]+$" :: Bool) &&
-- And bounds are equal or better than the bounds given by Why3 for Pi
lb >= (7074237752028440.0 / 2251799813685248.0) &&
hasUB var f]
where
lb = numer / denom
aux (FComp {}) = []
aux (FConn {}) = []
aux (FNot _) = []
aux FTrue = []
aux FFalse = []
hasUB :: String -> F -> Bool
hasUB piVar (FComp Lt (Var otherVar) (EBinOp Div (Lit numer) (Lit denom))) =
piVar == otherVar && ub <= (7074237752028441.0 / 2251799813685248.0)
where
ub = numer / denom
hasUB piVar (FConn And f1 f2) = hasUB piVar f1 || hasUB piVar f2
hasUB _ (FComp {}) = False
hasUB _ (FConn {}) = False
hasUB _ (FNot _) = False
hasUB _ FTrue = False
hasUB _ FFalse = False
|Derive ranges for a VC ( Implication where a CNF implies a goal )
-- Remove anything which refers to a variable for which we cannot derive ranges
-- If the goal contains underivable variables, return Nothing
deriveVCRanges :: F -> [(String, String)] -> Maybe (F, TypedVarMap)
deriveVCRanges vc varsWithTypes =
case filterOutVars simplifiedF underivableVariables False of
Just filteredF -> Just (filteredF, safelyRoundTypedVarMap typedDerivedVarMap)
Nothing -> Nothing
where
integerVariables = findIntegerVariables varsWithTypes
(simplifiedFUnchecked, derivedVarMapUnchecked, underivableVariables) = deriveBoundsAndSimplify vc
-- (piVars, derivedVarMap) = findRealPiVars derivedVarMapUnchecked
(piVars, derivedVarMap) = ([], derivedVarMapUnchecked)
typedDerivedVarMap = unsafeVarMapToTypedVarMap derivedVarMap integerVariables
-- safelyRoundTypedVarMap = id
safelyRoundTypedVarMap [] = []
safelyRoundTypedVarMap ((TypedVar (varName, (leftBound, rightBound)) Real) : vars) =
let
leftBoundRoundedDown = rational . fst . endpoints $ mpBallP (prec 23) leftBound
rightBoundRoundedUp = rational . snd . endpoints $ mpBallP (prec 23) rightBound
newBound = TypedVar (varName, (leftBoundRoundedDown, rightBoundRoundedUp)) Real
in
newBound : safelyRoundTypedVarMap vars
safelyRoundTypedVarMap (vi@(TypedVar _ Integer) : vars) = vi : safelyRoundTypedVarMap vars
-- simplifiedF = substVarsWithPi piVars simplifiedFUnchecked
simplifiedF = simplifiedFUnchecked
-- TODO: Would be good to include a warning when this happens
-- Could also make this an option
First elem are the variables which can be assumed to be real pi
Second elem is the varMap without the real pi vars
findRealPiVars :: VarMap -> ([String], VarMap)
findRealPiVars [] = ([], [])
findRealPiVars (varWithBounds@(var, (l, r)) : vars) =
if
-- If variable is pi or pi# where # is a number
(var =~ "^pi$|^pi[0-9]+$" :: Bool) &&
-- And bounds are equal or better than the bounds given by Why3 for Pi
l >= (7074237752028440.0 / 2251799813685248.0) && r <= (7074237752028441.0 / 2251799813685248.0) &&
-- And the type of the variable is Real
(lookup var varsWithTypes == Just "Real")
then (\(foundPiVars, varMapWithoutPi) -> ((var : foundPiVars), varMapWithoutPi)) $ findRealPiVars vars
else (\(foundPiVars, varMapWithoutPi) -> (foundPiVars, (varWithBounds : varMapWithoutPi))) $ findRealPiVars vars
substVarsWithPi :: [String] -> F -> F
substVarsWithPi [] f = f
substVarsWithPi (v : _) f = substVarFWithE v f Pi
-- |Safely filter our terms that contain underivable variables.
Need to preserve unsat terms , so we can safely remove x in FConn And x y if x contains underivable variables .
We can not safely remove x from FConn Or x y if x contains underivable variables
-- (since x may be sat and y may be unsat, filtering out x would give an incorrect unsat result), so we remove the whole term
-- Reverse logic as appropriate when a term is negated
filterOutVars :: F -> [String] -> Bool -> Maybe F
filterOutVars (FConn And f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn And ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FConn Or f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn Or ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn Impl f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn Impl ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn And f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn And ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn Or f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn Or ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FConn Impl f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn Impl ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FNot f) vars isNegated = FNot <$> filterOutVars f vars (not isNegated)
filterOutVars (FComp op e1 e2) vars _isNegated =
if eContainsVars vars e1 || eContainsVars vars e2
then Nothing
else Just (FComp op e1 e2)
filterOutVars FTrue _ _ = Just FTrue
filterOutVars FFalse _ _ = Just FFalse
eContainsVars :: [String] -> E -> Bool
eContainsVars vars (Var var) = var `elem` vars
eContainsVars _ (Lit _) = False
eContainsVars _ Pi = False
eContainsVars vars (EBinOp _ e1 e2) = eContainsVars vars e1 || eContainsVars vars e2
eContainsVars vars (EUnOp _ e) = eContainsVars vars e
eContainsVars vars (PowI e _) = eContainsVars vars e
eContainsVars vars (Float32 _ e) = eContainsVars vars e
eContainsVars vars (Float64 _ e) = eContainsVars vars e
eContainsVars vars (Float _ e) = eContainsVars vars e
eContainsVars vars (RoundToInteger _ e) = eContainsVars vars e
fContainsVars :: [String] -> F -> Bool
fContainsVars vars (FConn _ f1 f2) = fContainsVars vars f1 || fContainsVars vars f2
fContainsVars vars (FComp _ e1 e2) = eContainsVars vars e1 || eContainsVars vars e2
fContainsVars vars (FNot f) = fContainsVars vars f
fContainsVars _ FTrue = False
fContainsVars _ FFalse = False
inequalityEpsilon :: Rational
inequalityEpsilon = 0.000000001
inequalityEpsilon = 1/(2 ^ 23 )
findVarEqualities :: F -> [(String, E)]
findVarEqualities (FConn And f1 f2) = findVarEqualities f1 ++ findVarEqualities f2
findVarEqualities FConn {} = []
findVarEqualities (FComp Eq (Var v) e2) = [(v, e2)]
findVarEqualities (FComp Eq e1 (Var v)) = [(v, e1)]
findVarEqualities FComp {} = []
findVarEqualities (FNot _) = [] -- Not EQ, means we can't do anything here?
findVarEqualities FTrue = []
findVarEqualities FFalse = []
-- |Filter out var equalities which rely on themselves
filterOutCircularVarEqualities :: [(String, E)] -> [(String, E)]
filterOutCircularVarEqualities = filter (\(v, e) -> v `notElem` findVariablesInExpressions e)
-- |Filter out var equalities which occur multiple times by choosing the var equality with the smallest length
filterOutDuplicateVarEqualities :: [(String, E)] -> [(String, E)]
filterOutDuplicateVarEqualities [] = []
filterOutDuplicateVarEqualities ((v, e) : vs) =
case partition (\(v',_) -> v == v') vs of
([], _) -> (v, e) : filterOutDuplicateVarEqualities vs
(matchingEqualities, otherEqualities) ->
let shortestVarEquality = head $ sortBy (\(_, e1) (_, e2) -> P.compare (lengthE e1) (lengthE e2)) $ (v, e) : matchingEqualities
in shortestVarEquality : filterOutDuplicateVarEqualities otherEqualities
FIXME : subst one at a time
substAllEqualities :: F -> F
substAllEqualities = recursivelySubstVars
where
recursivelySubstVars f@(FConn Impl context _) =
case filteredVarEqualities of
[] -> f
_ -> if f P.== substitutedF then f else recursivelySubstVars . simplifyF $ substitutedF -- TODO: make this a var
where
substitutedF = substVars filteredVarEqualities f
filteredVarEqualities = (filterOutDuplicateVarEqualities . filterOutCircularVarEqualities) varEqualities
varEqualities = findVarEqualities context
recursivelySubstVars f =
case filteredVarEqualities of
[] -> f
_ -> if f P.== substitutedF then f else recursivelySubstVars . simplifyF $ substitutedF
where
substitutedF = substVars filteredVarEqualities f
filteredVarEqualities = (filterOutDuplicateVarEqualities . filterOutCircularVarEqualities) varEqualities
varEqualities = findVarEqualities f
substVars [] f = f
substVars ((v, e) : _) f = substVarFWithE v f e
addVarMapBoundsToF :: F -> TypedVarMap -> F
addVarMapBoundsToF f [] = f
addVarMapBoundsToF f (TypedVar (v, (l, r)) _ : vm) = FConn And boundAsF $ addVarMapBoundsToF f vm
where
boundAsF = FConn And (FComp Ge (Var v) (Lit l)) (FComp Le (Var v) (Lit r))
eliminateFloatsAndSimplifyVC :: F -> TypedVarMap -> Bool -> FilePath -> IO F
eliminateFloatsAndSimplifyVC vc typedVarMap strengthenVC fptaylorPath =
do
vcWithoutFloats <- eliminateFloatsF vc (typedVarMapToVarMap typedVarMap) strengthenVC fptaylorPath
let typedVarMapAsMap = M.fromList $ map (\(TypedVar (varName, (leftBound, rightBound)) _) -> (varName, (Just leftBound, Just rightBound))) typedVarMap
let simplifiedVCWithoutFloats = (simplifyF . evalF_comparisons typedVarMapAsMap) vcWithoutFloats
return simplifiedVCWithoutFloats
parseVCToF :: FilePath -> FilePath -> IO (Maybe (F, TypedVarMap))
parseVCToF filePath fptaylorPath =
do
parsedFile <- parseSMT2 filePath
case processVC parsedFile of
Just (vc, varTypes) ->
let
simplifiedVC = (symbolicallySubstitutePiVars . substAllEqualities . simplifyF) vc
mDerivedVCWithRanges = deriveVCRanges simplifiedVC varTypes
in
case mDerivedVCWithRanges of
Just (derivedVC, derivedRanges) ->
do
-- The file we are given is assumed to be a contradiction, so weaken the VC
let strengthenVC = False
vcWithoutFloats <- eliminateFloatsF derivedVC (typedVarMapToVarMap derivedRanges) strengthenVC fptaylorPath
let vcWithoutFloatsWithBounds = addVarMapBoundsToF vcWithoutFloats derivedRanges
case deriveVCRanges vcWithoutFloatsWithBounds varTypes of
Just (simplifiedVCWithoutFloats, finalDerivedRanges) -> return $ Just (simplifiedVCWithoutFloats, finalDerivedRanges)
Nothing -> error "Error deriving bounds again after floating-point elimination"
Nothing -> return Nothing
Nothing -> return Nothing
parseVCToSolver :: FilePath -> FilePath -> (F -> TypedVarMap -> String) -> Bool -> IO (Maybe String)
parseVCToSolver filePath fptaylorPath proverTranslator negateVC =
do
parsedFile <- parseSMT2 filePath
case processVC parsedFile of
Just (vc, varTypes) ->
let
simplifiedVC = (substAllEqualities . simplifyF) vc
mDerivedVCWithRanges = deriveVCRanges simplifiedVC varTypes
in
case mDerivedVCWithRanges of
Just (derivedVC, derivedRanges) ->
do
let strengthenVC = False
vcWithoutFloats <- eliminateFloatsF derivedVC (typedVarMapToVarMap derivedRanges) strengthenVC fptaylorPath
let vcWithoutFloatsWithBounds = addVarMapBoundsToF vcWithoutFloats derivedRanges
case deriveVCRanges vcWithoutFloatsWithBounds varTypes of
Just (simplifiedVCWithoutFloats, finalDerivedRanges) ->
return $ Just (
proverTranslator
(
if negateVC
then
case simplifiedVCWithoutFloats of
Eliminate double not
_ -> FNot simplifiedVCWithoutFloats
else simplifiedVCWithoutFloats
)
finalDerivedRanges
)
Nothing -> error "Error deriving bounds again after floating-point elimination"
return $ Just ( proverTranslator ( if negateVC then simplifyF ( FNot simplifiedVCWithoutFloats ) else ) derivedRanges )
Nothing -> return Nothing
Nothing -> return Nothing
| null | https://raw.githubusercontent.com/rasheedja/PropaFP/c7680a48c9524768ac113ab5ca0e179dc2f315c6/src/PropaFP/Parsers/Smt.hs | haskell | |Find assertions in a parsed expression
Assertions are Application types with the operator being a Variable equal to "assert"
Assertions only have one 'operands'
findAssertions ((LD.Application (LD.Variable var) [operands]) : expressions) = operands : findAssertions expressions
|Find function declarations in a parsed expression
Function declarations are Application types with the operator being a Variable equal to "declare-fun"
- Operand 1 is the name of the function
- Operand 2 is an Application type which can be thought of as the parameters of the functions
- Operand 3 is the type of the function
|Finds goals in assertion operands
Goals are S-Expressions with a top level 'not'
|Takes the last element from a list of assertions
We assume that the last element is the goal
FIXME: Unsafe. If asserts is empty, this will fail
safelyTypeExpression :: String -> [(String, ([String], String))] -> E -> E
Just (inputs, output)
parseIte :: LD.Expression -> LD.Expression -> LD.Expression -> Maybe F
Single param operators
Ops with E params
if-then-else operator with F types
Symbols/Literals
These should be parsed to F
These should be parsed to F
RoundToInt
Are these suffixes consistent?
Float functions
"fp.to_real" -> Just e
"to_real" -> Just e
"value" -> Just e
Undefined functions
case lookup functionName functionsWithInputsAndOutputs of
Just ([inputType], outputType) ->
case lookup functionName functionsWithInputsAndOutputs of
Nothing -> (Nothing, Nothing)
case mInputTypes of
Just [inputType] ->
case inputType of
" Float32 " - > Float32 RNE functionArg
-- "Float64" -> Float64 RNE functionArg
Do not deal with multiple param args for one param functions . TODO : Check if these can occur , i.e. something like RoundingMode Float32
TODO : Make these Nothing if we ca n't deal with them
TODO : Make these Nothing if we ca n't deal with them
FIXME: Should match on other possible names. Real/real Int/int/integer, etc. I've only seen these alt names in function definitions/axioms, not assertions, but would still be more safe.
FIXME: Round here?
These should be floats, which we cannot deal with for now
No type given, assume real
Nothing -> functionAsExpression functionArg
FIXME: remove this? not used with cvc4 driver?
Why3 will type check that the input is an integer, making these safe
FIXME: remove int pow? only use int pow if actually specified?
Just ([input1, "Int"], output) ->
let
mExactPowExpression =
then case e2 of
else Nothing
in case mExactPowExpression of
Just exactPowExpression -> case output of
"Real" -> Just exactPowExpression
"Int" -> Just $ RoundToInteger RNE exactPowExpression
_ -> Nothing
Nothing -> Nothing
Nothing -> -- No input/output, treat as real pow
case e2 of
_ -> Nothing
TODO : might be worth implementing
-- No input/output, treat as real mod
Nothing -> Just $ EBinOp Mod e1 e2
_ -> Nothing
Float bits to Rational
case operator of
SPARK Reals
"fp.to_real" -> Nothing
_ -> -- Known ops
Floating-point ops
|Replace function guards which are known to be always true with true.
|Replace function guard which is known to be always true with true.
t
It is safe to treat integers and rationals as reals
|Tries to determine whether a Float operation is single or double precision
by searching for the type of all variables appearing in the function. If the
|Find the type for the given variables
Type is looked for in the supplied map
If all found types match, return this type
|Process a parsed list of expressions to a VC.
If the parsing mode is Why3, everything in the context implies the goal (empty context means we only have a goal).
If the goal cannot be parsed, we return Nothing.
If the parsing mode is CNF, parse all assertions into a CNF. If any assertion cannot be parsed, return Nothing.
|Looks for pi vars (vars named pi/pi{i} where {i} is some integer) and symbolic bounds.
If variable is pi or pi# where # is a number
And bounds are equal or better than the bounds given by Why3 for Pi
Remove anything which refers to a variable for which we cannot derive ranges
If the goal contains underivable variables, return Nothing
(piVars, derivedVarMap) = findRealPiVars derivedVarMapUnchecked
safelyRoundTypedVarMap = id
simplifiedF = substVarsWithPi piVars simplifiedFUnchecked
TODO: Would be good to include a warning when this happens
Could also make this an option
If variable is pi or pi# where # is a number
And bounds are equal or better than the bounds given by Why3 for Pi
And the type of the variable is Real
|Safely filter our terms that contain underivable variables.
(since x may be sat and y may be unsat, filtering out x would give an incorrect unsat result), so we remove the whole term
Reverse logic as appropriate when a term is negated
Not EQ, means we can't do anything here?
|Filter out var equalities which rely on themselves
|Filter out var equalities which occur multiple times by choosing the var equality with the smallest length
TODO: make this a var
The file we are given is assumed to be a contradiction, so weaken the VC | # LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
# LANGUAGE LambdaCase #
module PropaFP.Parsers.Smt where
import MixedTypesNumPrelude hiding (unzip)
import qualified Prelude as P
import System.IO.Unsafe
import PropaFP.Expression
import qualified PropaFP.Parsers.Lisp.Parser as LP
import qualified PropaFP.Parsers.Lisp.DataTypes as LD
import Data.Char (digitToInt)
import Data.Word
import qualified Data.ByteString.Lazy as B
import Data.Binary.Get
import Data.Maybe (mapMaybe)
import PropaFP.VarMap
import PropaFP.DeriveBounds
import PropaFP.EliminateFloats
import PropaFP.Eliminator (minMaxAbsEliminatorECNF, minMaxAbsEliminator)
import Data.List (nub, sort, isPrefixOf, sortBy, partition, foldl')
import Data.List.NonEmpty (unzip)
import Control.Arrow ((&&&))
import Debug.Trace
import PropaFP.Translators.DReal (formulaAndVarMapToDReal)
import Text.Regex.TDFA ( (=~) )
import Data.Ratio
import PropaFP.DeriveBounds
import qualified Data.Map as M
import AERN2.MP (endpoints, mpBallP, prec)
data ParsingMode = Why3 | CNF
parser :: String -> [LD.Expression]
parser = LP.analyzeExpressionSequence . LP.parseSequence . LP.tokenize
parseSMT2 :: FilePath -> IO [LD.Expression]
parseSMT2 filePath = fmap parser $ P.readFile filePath
findAssertions :: [LD.Expression] -> [LD.Expression]
findAssertions [] = []
findAssertions [ LD.Application ( LD.Variable " assert " ) [ operands ] ] = [ operands ]
findAssertions ((LD.Application (LD.Variable "assert") [operands]) : expressions) = operands : findAssertions expressions
findAssertions (e : expressions) = findAssertions expressions
findFunctionInputsAndOutputs :: [LD.Expression] -> [(String, ([String], String))]
findFunctionInputsAndOutputs [] = []
findFunctionInputsAndOutputs ((LD.Application (LD.Variable "declare-fun") [LD.Variable fName, fInputsAsExpressions, LD.Variable fOutputs]) : expressions) =
(fName, (expressionInputsAsString fInputsAsExpressions, fOutputs)) : findFunctionInputsAndOutputs expressions
where
expressionInputsAsString :: LD.Expression -> [String]
expressionInputsAsString (LD.Application (LD.Variable inputTypeAsString) remainingInputsAsExpression) = inputTypeAsString : concatMap expressionInputsAsString remainingInputsAsExpression
expressionInputsAsString (LD.Variable inputTypeAsString) = [inputTypeAsString]
expressionInputsAsString _ = []
findFunctionInputsAndOutputs (_ : expressions) = findFunctionInputsAndOutputs expressions
Function declarations contain 3 operands
If the function has no paramters , this operand is LD.Null
findDeclarations :: [LD.Expression] -> [LD.Expression]
findDeclarations [] = []
findDeclarations (declaration@(LD.Application (LD.Variable "declare-fun") _) : expressions) = declaration : findDeclarations expressions
findDeclarations (_ : expressions) = findDeclarations expressions
findVariables :: [LD.Expression] -> [(String, String)]
findVariables [] = []
findVariables (LD.Application (LD.Variable "declare-const") [LD.Variable varName, LD.Variable varType] : expressions)
= (varName, varType) : findVariables expressions
findVariables (LD.Application (LD.Variable "declare-fun") [LD.Variable varName, LD.Null, LD.Variable varType] : expressions)
= (varName, varType) : findVariables expressions
findVariables (_ : expressions) = findVariables expressions
findIntegerVariables :: [(String, String)] -> [(String, VarType)]
findIntegerVariables [] = []
findIntegerVariables ((v,t) : vs) =
if "Int" `isPrefixOf` t || "int" `isPrefixOf` t
then (v, Integer) : findIntegerVariables vs
else findIntegerVariables vs
findGoalsInAssertions :: [LD.Expression] -> [LD.Expression]
findGoalsInAssertions [] = []
findGoalsInAssertions ((LD.Application (LD.Variable operator) operands) : assertions) =
if operator == "not"
Take head of operands since not has only one operand
else findGoalsInAssertions assertions
findGoalsInAssertions (_ : assertions) = findGoalsInAssertions assertions
takeGoalFromAssertions :: [LD.Expression] -> (LD.Expression, [LD.Expression])
takeGoalFromAssertions asserts = (goal, assertsWithoutGoal)
where
numberOfAssertions = length asserts
assertsWithoutGoal = take (numberOfAssertions - 1) asserts
safelyTypeExpression smtFunction functionsWithInputsAndOutputs exactExpression =
case lookup smtFunction functionsWithInputsAndOutputs of
|Attempts to parse FComp Ops , i.e. parse bool_eq to Just ( )
parseFCompOp :: String -> Maybe (E -> E -> F)
parseFCompOp operator =
case operator of
n
| n `elem` [">=", "fp.geq", "oge", "oge__logic"] || (n =~ "^bool_ge$|^bool_ge[0-9]+$" :: Bool) -> Just $ FComp Ge
| n `elem` [">", "fp.gt", "ogt", "ogt__logic"] || (n =~ "^bool_gt$|^bool_gt[0-9]+$" :: Bool) -> Just $ FComp Gt
| n `elem` ["<=", "fp.leq", "ole", "ole__logic"] || (n =~ "^bool_le$|^bool_le[0-9]+$" :: Bool) -> Just $ FComp Le
| n `elem` ["<", "fp.lt", "olt", "olt__logic"] || (n =~ "^bool_lt$|^bool_lt[0-9]+$" :: Bool) -> Just $ FComp Lt
| n `elem` ["=", "fp.eq"] || (n =~ "^bool_eq$|^bool_eq[0-9]+$|^user_eq$|^user_eq[0-9]+$" :: Bool) -> Just $ FComp Eq
| "bool_neq" `isPrefixOf` n -> Just $ \e1 e2 -> FNot (FComp Eq e1 e2)
_ -> Nothing
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs Nothing =
case termToF cond functionsWithInputsAndOutputs of
Just condF ->
case (termToF thenTerm functionsWithInputsAndOutputs, termToF elseTerm functionsWithInputsAndOutputs) of
(Just thenTermF, Just elseTermF) ->
Just $ FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) elseTermF)
(_, _) -> Nothing
Nothing -> Nothing
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just compTerm) =
case termToF cond functionsWithInputsAndOutputs of
(Just condF) ->
case (termToE thenTerm functionsWithInputsAndOutputs, termToE elseTerm functionsWithInputsAndOutputs) of
(Just thenTermE, Just elseTermE) ->
Just $ FConn And
(FConn Impl condF (compTerm thenTermE))
(FConn Impl (FNot condF) (compTerm elseTermE))
(Just thenTermE, _) ->
case elseTerm of
LD.Application (LD.Variable "ite") [elseCond, elseThenTerm, elseElseTerm] ->
case parseIte elseCond elseThenTerm elseElseTerm functionsWithInputsAndOutputs (Just compTerm) of
Just elseTermF -> Just $
FConn And
(FConn Impl condF (compTerm thenTermE))
(FConn Impl (FNot condF) elseTermF)
_ -> Nothing
_ -> Nothing
(_, Just elseTermE) ->
case thenTerm of
LD.Application (LD.Variable "ite") [thenCond, thenThenTerm, thenElseTerm] ->
case parseIte thenCond thenThenTerm thenElseTerm functionsWithInputsAndOutputs (Just compTerm) of
Just thenTermF -> Just $
FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) (compTerm elseTermE))
_ -> Nothing
_ -> Nothing
(_, _) ->
case (thenTerm, elseTerm) of
(LD.Application (LD.Variable "ite") [thenCond, thenThenTerm, thenElseTerm], LD.Application (LD.Variable "ite") [elseCond, elseThenTerm, elseElseTerm]) ->
case (parseIte thenCond thenThenTerm thenElseTerm functionsWithInputsAndOutputs (Just compTerm), parseIte elseCond elseThenTerm elseElseTerm functionsWithInputsAndOutputs (Just compTerm)) of
(Just thenTermF, Just elseTermF) -> Just $
FConn And
(FConn Impl condF thenTermF)
(FConn Impl (FNot condF) elseTermF)
(_, _) -> Nothing
(_, _) -> Nothing
Nothing -> Nothing
termToF :: LD.Expression -> [(String, ([String], String))] -> Maybe F
Just e ->
case operator of
"fp.isFinite32" ->
let maxFloat = (2.0 - (1/(2^23))) * (2^127)
minFloat = negate maxFloat
in
Just $ FConn And (FComp Le (Lit minFloat) e) (FComp Le e (Lit maxFloat))
"fp.isFinite64" ->
let maxFloat = (2.0 - (1/(2^52))) * (2^1023)
minFloat = negate maxFloat
in
Just $ FConn And (FComp Le (Lit minFloat) e) (FComp Le e (Lit maxFloat))
_ -> Nothing
Nothing ->
case termToF op functionsWithInputsAndOutputs of
Just f ->
case operator of
"not" -> Just $ FNot f
_ -> Nothing
_ -> Nothing
Two param operations
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
case parseFCompOp operator of
Just fCompOp -> Just $ fCompOp e1 e2
_ -> Nothing
(_, _) ->
case (termToF op1 functionsWithInputsAndOutputs, termToF op2 functionsWithInputsAndOutputs) of
(Just f1, Just f2) ->
case operator of
"and" -> Just $ FConn And f1 f2
"or" -> Just $ FConn Or f1 f2
"=>" -> Just $ FConn Impl f1 f2
"=" -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
n
| "bool_eq" `isPrefixOf` n -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
| "bool_neq" `isPrefixOf` n -> Just $ FNot $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
| "user_eq" `isPrefixOf` n -> Just $ FConn And (FConn Impl f1 f2) (FConn Impl f2 f1)
_ -> Nothing
where it is used as an expression
(_, _) ->
case (op1, termToE op2 functionsWithInputsAndOutputs) of
(LD.Application (LD.Variable "ite") [cond, thenTerm, elseTerm], Just e2) ->
case parseFCompOp operator of
Just fCompOp -> parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just (\e -> fCompOp e e2))
Nothing -> Nothing
(_, _) ->
case (termToE op1 functionsWithInputsAndOutputs, op2) of
(Just e1, LD.Application (LD.Variable "ite") [cond, thenTerm, elseTerm]) ->
case parseFCompOp operator of
Just fCompOp -> parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs (Just (\e -> fCompOp e1 e))
Nothing -> Nothing
(_, _) -> Nothing
parseIte cond thenTerm elseTerm functionsWithInputsAndOutputs Nothing
termToF (LD.Variable "true") functionsWithInputsAndOutputs = Just FTrue
termToF (LD.Variable "false") functionsWithInputsAndOutputs = Just FFalse
termToF _ _ = Nothing
termToE :: LD.Expression -> [(String, ([String], String))] -> Maybe E
Parse 4 * atan(1 ) as Pi ( used by our dReal SMT translator )
termToE (LD.Application (LD.Variable "*") [LD.Number 4, LD.Application (LD.Variable "atan") [LD.Number 1]]) functionsWithInputsAndOutputs = Just $ Pi
termToE (LD.Variable var) functionsWithInputsAndOutputs = Just $ Var var
termToE (LD.Number num) functionsWithInputsAndOutputs = Just $ Lit num
one param PropaFP translator functions
termToE (LD.Application (LD.Variable "to_int_rne") [p]) functionsWithInputsAndOutputs = RoundToInteger RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtp") [p]) functionsWithInputsAndOutputs = RoundToInteger RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtn") [p]) functionsWithInputsAndOutputs = RoundToInteger RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rtz") [p]) functionsWithInputsAndOutputs = RoundToInteger RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "to_int_rna") [p]) functionsWithInputsAndOutputs = RoundToInteger RNA <$> termToE p functionsWithInputsAndOutputs
Float32
termToE (LD.Application (LD.Variable "float32_rne") [p]) functionsWithInputsAndOutputs = Float32 RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtp") [p]) functionsWithInputsAndOutputs = Float32 RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtn") [p]) functionsWithInputsAndOutputs = Float32 RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rtz") [p]) functionsWithInputsAndOutputs = Float32 RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float32_rna") [p]) functionsWithInputsAndOutputs = Float32 RNA <$> termToE p functionsWithInputsAndOutputs
Float64
termToE (LD.Application (LD.Variable "float64_rne") [p]) functionsWithInputsAndOutputs = Float64 RNE <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtp") [p]) functionsWithInputsAndOutputs = Float64 RTP <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtn") [p]) functionsWithInputsAndOutputs = Float64 RTN <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rtz") [p]) functionsWithInputsAndOutputs = Float64 RTZ <$> termToE p functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "float64_rna") [p]) functionsWithInputsAndOutputs = Float64 RNA <$> termToE p functionsWithInputsAndOutputs
one param functions
termToE (LD.Application (LD.Variable operator) [op]) functionsWithInputsAndOutputs =
case termToE op functionsWithInputsAndOutputs of
Nothing -> Nothing
Just e -> case operator of
n
| (n =~ "^real_pi$|^real_pi[0-9]+$" :: Bool) -> Just Pi
| (n =~ "^abs$|^abs[0-9]+$" :: Bool) -> Just $ EUnOp Abs e
| (n =~ "^sin$|^sin[0-9]+$|^real_sin$|^real_sin[0-9]+$" :: Bool) -> Just $ EUnOp Sin e
| (n =~ "^cos$|^cos[0-9]+$|^real_cos$|^real_cos[0-9]+$" :: Bool) -> Just $ EUnOp Cos e
| (n =~ "^sqrt$|^sqrt[0-9]+$|^real_square_root$|^real_square_root[0-9]+$" :: Bool) -> Just $ EUnOp Sqrt e
| (n =~ "^fp.to_real$|^fp.to_real[0-9]+$|^to_real$|^to_real[0-9]+$" :: Bool) -> Just e
"-" -> Just $ EUnOp Negate e
SPARK Reals functions
"from_int" -> Just e
Some to_int functions . different suffixes ( 1 , 2 , etc . )
e.g. In one file , to_int1 : : Float - > Int
to_int2 : : Int
"fp.abs" -> Just $ EUnOp Abs e
"fp.neg" -> Just $ EUnOp Negate e
"fp.isNormal" -> Nothing
"fp.isSubnormal" -> Nothing
"fp.isZero" -> Nothing
"fp.isNaN" -> Nothing
"fp.isPositive" -> Nothing
"fp.isNegative" -> Nothing
"fp.isIntegral32" -> Nothing
"fp.isIntegral64" -> Nothing
_ -> Nothing
where
deriveTypeForOneArgFunctions :: String -> (E -> E) -> E -> Maybe E
deriveTypeForOneArgFunctions functionName functionAsExpression functionArg =
let
(mInputTypes, mOutputType) = unzip $ lookup functionName functionsWithInputsAndOutputs
Just ( inputTypes , outputType ) - > ( Just inputTypes , Just outputType )
newFunctionArg = functionArg
mNewFunctionAsExpression =
case mOutputType of
Just outputType ->
case outputType of
in
case mNewFunctionAsExpression of
Just newFunctionAsExpression -> Just $ newFunctionAsExpression newFunctionArg
Nothing -> Nothing
two param PropaFP translator functions
termToE (LD.Application (LD.Variable "min") [p1, p2]) functionsWithInputsAndOutputs = EBinOp Min <$> termToE p1 functionsWithInputsAndOutputs <*> termToE p2 functionsWithInputsAndOutputs
termToE (LD.Application (LD.Variable "max") [p1, p2]) functionsWithInputsAndOutputs = EBinOp Max <$> termToE p1 functionsWithInputsAndOutputs <*> termToE p2 functionsWithInputsAndOutputs
two param functions
params are either two different E types , or one param is a rounding mode and another is the arg
termToE (LD.Application (LD.Variable operator) [op1, op2]) functionsWithInputsAndOutputs =
case (parseRoundingMode op1, termToE op2 functionsWithInputsAndOutputs) of
(Just roundingMode, Just e) ->
case operator of
n
| (n =~ "^to_int$|^to_int[0-9]+$" :: Bool) -> Just $ RoundToInteger roundingMode e
| (n =~ "^of_int$|^of_int[0-9]+$" :: Bool) ->
case lookup n functionsWithInputsAndOutputs of
Just (_, outputType) ->
case outputType of
| o `elem` ["Float32", "single"] -> Just $ Float32 roundingMode e
| o `elem` ["Float64", "double"] -> Just $ Float64 roundingMode e
| o `elem` ["Real", "real"] -> Just e
_ -> Nothing
_ -> Nothing
"fp.roundToIntegral" -> Just $ RoundToInteger roundingMode e
_ -> Nothing
_ ->
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
case operator of
n
" o ... " functions are from SPARK Reals
| n `elem` ["+", "oadd", "oadd__logic"] -> Just $ EBinOp Add e1 e2
| n `elem` ["-", "osubtract", "osubtract__logic"] -> Just $ EBinOp Sub e1 e2
| n `elem` ["*", "omultiply", "omultiply__logic"] -> Just $ EBinOp Mul e1 e2
| n `elem` ["/", "odivide", "odivide__logic"] -> Just $ EBinOp Div e1 e2
| n == "^" -> Just $ EBinOp Pow e1 e2
case lookup n functionsWithInputsAndOutputs of
Just ( [ " Real " , " Real " ] , " Real " ) - > Just $ EBinOp Pow e1 e2
if input1 = = " Int " || input1 = = " Real "
Lit l2 - > if denominator l2 = = 1.0 then Just $ PowI e1 ( numerator l2 ) else Just $ EBinOp Pow e1 e2
_ - > Just $ EBinOp Pow e1 e2
Lit l2 - > if denominator l2 = = 1.0 then Just $ PowI e1 ( numerator l2 ) else Just $ EBinOp Pow e1 e2
_ - > Just $ EBinOp Pow e1 e2
| (n =~ "^mod$|^mod[0-9]+$" :: Bool) -> Just $ EBinOp Mod e1 e2
case lookup n functionsWithInputsAndOutputs of
Just ( [ " Real " , " Real " ] , " Real " ) - > Just $ EBinOp Mod e1 e2
_ -> Nothing
(_, _) -> Nothing
termToE (LD.Application (LD.Variable "fp") [LD.Variable sSign, LD.Variable sExponent, LD.Variable sMantissa]) functionsWithInputsAndOutputs =
let
bSign = drop 2 sSign
bExponent = drop 2 sExponent
bMantissa = drop 2 sMantissa
bFull = bSign ++ bExponent ++ bMantissa
Read a string of ( ' 1 ' or ' 0 ' ) where the first digit is the most significant
The digit parameter denotes the current digit , should be equal to length of the first param at all times
readBits :: String -> Integer -> Integer
readBits [] _ = 0
readBits (bit : bits) digit = digitToInt bit * (2 ^ (digit - 1)) + readBits bits (digit - 1)
bitsToWord8 :: String -> [Word8]
bitsToWord8 bits =
let wordS = take 8 bits
rem = drop 8 bits
wordV = readBits wordS 8
in
P.fromInteger wordV : bitsToWord8 rem
bsFloat = B.pack $ bitsToWord8 bFull
in
if all (`elem` "01") bFull
then
case length bFull of
32 -> Just $ Lit $ toRational $ runGet getFloatbe bsFloat
64 -> Just $ Lit $ toRational $ runGet getDoublebe bsFloat
32 - > Just $ Float32 RNE $ Lit $ toRational $ runGet getFloatbe bsFloat
64 - > Just $ Float64 RNE $ Lit $ toRational $ runGet
_ -> Nothing
else Nothing
Float functions , three params . Other three param functions should be placed before here
termToE (LD.Application (LD.Variable operator) [roundingMode, op1, op2]) functionsWithInputsAndOutputs =
case (termToE op1 functionsWithInputsAndOutputs, termToE op2 functionsWithInputsAndOutputs) of
(Just e1, Just e2) ->
Just mode ->
case operator of
"fp.add" -> Just $ Float mode $ EBinOp Add e1 e2
"fp.sub" -> Just $ Float mode $ EBinOp Sub e1 e2
"fp.mul" -> Just $ Float mode $ EBinOp Mul e1 e2
"fp.div" -> Just $ Float mode $ EBinOp Div e1 e2
_ -> Nothing
Nothing -> Nothing
(_, _) -> Nothing
termToE _ _ = Nothing
collapseOrs :: [LD.Expression] -> [LD.Expression]
collapseOrs = map collapseOr
collapseOr :: LD.Expression -> LD.Expression
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "<") args1, LD.Application (LD.Variable "=") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable "<=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "=") args1, LD.Application (LD.Variable "<") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable "<=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable ">") args1, LD.Application (LD.Variable "=") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable ">=") args1
else orig
collapseOr orig@(LD.Application (LD.Variable "or") [LD.Application (LD.Variable "=") args1, LD.Application (LD.Variable ">") args2]) =
if args1 P.== args2
then LD.Application (LD.Variable ">=") args1
else orig
collapseOr (LD.Application operator args) = LD.Application operator (collapseOrs args)
collapseOr e = e
eliminateKnownFunctionGuards :: [LD.Expression] -> [LD.Expression]
eliminateKnownFunctionGuards = map eliminateKnownFunctionGuard
eliminateKnownFunctionGuard :: LD.Expression -> LD.Expression
eliminateKnownFunctionGuard orig@(LD.Application operator@(LD.Variable var) args@(guardedFunction : _)) =
let
knownGuardsRegex =
"^real_sin__function_guard$|^real_sin__function_guard[0-9]+$|" ++
"^real_cos__function_guard$|^real_cos__function_guard[0-9]+$|" ++
"^real_square_root__function_guard$|^real_square_root__function_guard[0-9]+$|" ++
"^real_pi__function_guard$|^real_pi__function_guard[0-9]+$"
in
if (var =~ knownGuardsRegex :: Bool)
then LD.Variable "true"
else LD.Application operator (eliminateKnownFunctionGuards args)
eliminateKnownFunctionGuard (LD.Application operator args) = LD.Application operator (eliminateKnownFunctionGuards args)
eliminateKnownFunctionGuard e = e
termsToF :: [LD.Expression] -> [(String, ([String], String))] -> [F]
termsToF es fs = mapMaybe (`termToF` fs) es
determineFloatTypeE :: E -> [(String, String)] -> Maybe E
determineFloatTypeE (EBinOp op e1 e2) varTypeMap = case determineFloatTypeE e1 varTypeMap of
Just p1 ->
case determineFloatTypeE e2 varTypeMap of
Just p2 -> Just $ EBinOp op p1 p2
Nothing -> Nothing
Nothing -> Nothing
determineFloatTypeE (EUnOp op e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ EUnOp op p
Nothing -> Nothing
determineFloatTypeE (PowI e i) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ PowI p i
Nothing -> Nothing
determineFloatTypeE (Float r e) varTypeMap = case mVariableType of
Just variableType ->
case variableType of
t
| t `elem` ["Float32", "single"] ->
case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float32 r p
Nothing -> Nothing
| t `elem` ["Float64", "double"] ->
case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float64 r p
Nothing -> Nothing
_ -> Nothing
Nothing -> Nothing
where
allVars = findVariablesInExpressions e
knownVarsWithPrecision = knownFloatVars e
knownVars = map fst knownVarsWithPrecision
unknownVars = filter (`notElem` knownVars) allVars
mVariableType = findVariableType unknownVars varTypeMap knownVarsWithPrecision Nothing
determineFloatTypeE (Float32 r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float32 r p
Nothing -> Nothing
determineFloatTypeE (Float64 r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ Float64 r p
Nothing -> Nothing
determineFloatTypeE (RoundToInteger r e) varTypeMap = case determineFloatTypeE e varTypeMap of
Just p -> Just $ RoundToInteger r p
Nothing -> Nothing
determineFloatTypeE Pi _ = Just Pi
determineFloatTypeE (Var v) varTypeMap = case lookup v varTypeMap of
Just variableType ->
case variableType of
| t ` elem ` [ " Float32 " , " single " ] - > Just $ Float32 RNE $ Var v
| t ` elem ` [ " Float64 " , " double " ] - > Just $ Float64 RNE $ Var v
_ -> Just $ Var v
determineFloatTypeE (Lit n) _ = Just $ Lit n
types match and are all either Float32 / Float64 , we can determine the type .
determineFloatTypeF :: F -> [(String, String)] -> Maybe F
determineFloatTypeF (FComp op e1 e2) varTypeMap = case (determineFloatTypeE e1 varTypeMap, determineFloatTypeE e2 varTypeMap) of
(Just p1, Just p2) -> Just $ FComp op p1 p2
(_, _) -> Nothing
determineFloatTypeF (FConn op f1 f2) varTypeMap = case (determineFloatTypeF f1 varTypeMap, determineFloatTypeF f2 varTypeMap) of
(Just p1, Just p2) -> Just $ FConn op p1 p2
(_, _) -> Nothing
determineFloatTypeF (FNot f) varTypeMap = case determineFloatTypeF f varTypeMap of
Just p -> Just $ FNot p
Nothing -> Nothing
determineFloatTypeF FTrue _ = Just FTrue
determineFloatTypeF FFalse _ = Just FFalse
findVariableType :: [String] -> [(String, String)] -> [(String, Integer)] -> Maybe String -> Maybe String
findVariableType [] _ [] mFoundType = mFoundType
findVariableType [] _ ((_, precision) : vars) mFoundType =
case mFoundType of
Just t ->
if (t `elem` ["Float32", "single"] && precision == 32) || ((t `elem` ["Float64", "double"]) && (precision == 64))
then findVariableType [] [] vars mFoundType
else Nothing
Nothing ->
case precision of
32 -> findVariableType [] [] vars (Just "Float32")
64 -> findVariableType [] [] vars (Just "Float64")
_ -> Nothing
findVariableType (v: vs) varTypeMap knownVarsWithPrecision mFoundType =
case lookup v varTypeMap of
Just t ->
if "Int" `isPrefixOf` t then
findVariableType vs varTypeMap knownVarsWithPrecision mFoundType
else
case mFoundType of
Just f -> if f == t then findVariableType vs varTypeMap knownVarsWithPrecision (Just t) else Nothing
Nothing -> findVariableType vs varTypeMap knownVarsWithPrecision (Just t)
Nothing -> Nothing
knownFloatVars :: E -> [(String, Integer)]
knownFloatVars e = removeConflictingVars . nub $ findAllFloatVars e
where
removeConflictingVars :: [(String, Integer)] -> [(String, Integer)]
removeConflictingVars [] = []
removeConflictingVars ((v, t) : vs) =
if v `elem` map fst vs
then removeConflictingVars $ filter (\(v', _) -> v /= v') vs
else (v, t) : removeConflictingVars vs
findAllFloatVars (EBinOp _ e1 e2) = knownFloatVars e1 ++ knownFloatVars e2
findAllFloatVars (EUnOp _ e) = knownFloatVars e
findAllFloatVars (PowI e _) = knownFloatVars e
findAllFloatVars (Float _ e) = knownFloatVars e
findAllFloatVars (Float32 _ (Var v)) = [(v, 32)]
findAllFloatVars (Float64 _ (Var v)) = [(v, 64)]
findAllFloatVars (Float32 _ e) = knownFloatVars e
findAllFloatVars (Float64 _ e) = knownFloatVars e
findAllFloatVars (RoundToInteger _ e) = knownFloatVars e
findAllFloatVars (Var _) = []
findAllFloatVars (Lit _) = []
findAllFloatVars Pi = []
findVariablesInFormula :: F -> [String]
findVariablesInFormula f = nub $ findVars f
where
findVars (FConn _ f1 f2) = findVars f1 ++ findVars f2
findVars (FComp _ e1 e2) = findVariablesInExpressions e1 ++ findVariablesInExpressions e2
findVars (FNot f1) = findVars f1
findVars FTrue = []
findVars FFalse = []
findVariablesInExpressions :: E -> [String]
findVariablesInExpressions (EBinOp _ e1 e2) = findVariablesInExpressions e1 ++ findVariablesInExpressions e2
findVariablesInExpressions (EUnOp _ e) = findVariablesInExpressions e
findVariablesInExpressions (PowI e _) = findVariablesInExpressions e
findVariablesInExpressions (Float _ e) = findVariablesInExpressions e
findVariablesInExpressions (Float32 _ e) = findVariablesInExpressions e
findVariablesInExpressions (Float64 _ e) = findVariablesInExpressions e
findVariablesInExpressions (RoundToInteger _ e) = findVariablesInExpressions e
findVariablesInExpressions (Var v) = [v]
findVariablesInExpressions (Lit _) = []
findVariablesInExpressions Pi = []
parseRoundingMode :: LD.Expression -> Maybe RoundingMode
parseRoundingMode (LD.Variable mode) =
case mode of
m
| m `elem` ["RNE", "NearestTiesToEven"] -> Just RNE
| m `elem` ["RTP", "Up"] -> Just RTP
| m `elem` ["RTN", "Down"] -> Just RTN
| m `elem` ["RTZ", "ToZero"] -> Just RTZ
| m `elem` ["RNA"] -> Just RNA
_ -> Nothing
parseRoundingMode _ = Nothing
If any assertion contains , return Nothing .
processVC :: [LD.Expression] -> Maybe (F, [(String, String)])
processVC parsedExpressions =
Just (foldAssertionsF assertionsF, variablesWithTypes)
where
assertions = findAssertions parsedExpressions
assertionsF = mapMaybe (`determineFloatTypeF` variablesWithTypes) $ (termsToF . eliminateKnownFunctionGuards . collapseOrs) assertions functionsWithInputsAndOutputs
variablesWithTypes = findVariables parsedExpressions
functionsWithInputsAndOutputs = findFunctionInputsAndOutputs parsedExpressions
foldAssertionsF :: [F] -> F
foldAssertionsF [] = error "processVC - foldAssertionsF: Empty list given"
foldAssertionsF [f] = f
foldAssertionsF (f : fs) = FConn And f (foldAssertionsF fs)
If the bounds are better than those given to the real pi in Why3 , replace the variable with exact pi .
symbolicallySubstitutePiVars :: F -> F
symbolicallySubstitutePiVars f = substVarsWithPi piVars f
where
piVars = nub (aux f)
substVarsWithPi :: [String] -> F -> F
substVarsWithPi [] f' = f'
substVarsWithPi (v : _) f' = substVarFWithE v f' Pi
aux :: F -> [String]
aux (FConn And f1 f2) = aux f1 ++ aux f2
aux (FComp Lt (EBinOp Div (Lit numer) (Lit denom)) (Var var)) =
[var |
(var =~ "^pi$|^pi[0-9]+$" :: Bool) &&
lb >= (7074237752028440.0 / 2251799813685248.0) &&
hasUB var f]
where
lb = numer / denom
aux (FComp {}) = []
aux (FConn {}) = []
aux (FNot _) = []
aux FTrue = []
aux FFalse = []
hasUB :: String -> F -> Bool
hasUB piVar (FComp Lt (Var otherVar) (EBinOp Div (Lit numer) (Lit denom))) =
piVar == otherVar && ub <= (7074237752028441.0 / 2251799813685248.0)
where
ub = numer / denom
hasUB piVar (FConn And f1 f2) = hasUB piVar f1 || hasUB piVar f2
hasUB _ (FComp {}) = False
hasUB _ (FConn {}) = False
hasUB _ (FNot _) = False
hasUB _ FTrue = False
hasUB _ FFalse = False
|Derive ranges for a VC ( Implication where a CNF implies a goal )
deriveVCRanges :: F -> [(String, String)] -> Maybe (F, TypedVarMap)
deriveVCRanges vc varsWithTypes =
case filterOutVars simplifiedF underivableVariables False of
Just filteredF -> Just (filteredF, safelyRoundTypedVarMap typedDerivedVarMap)
Nothing -> Nothing
where
integerVariables = findIntegerVariables varsWithTypes
(simplifiedFUnchecked, derivedVarMapUnchecked, underivableVariables) = deriveBoundsAndSimplify vc
(piVars, derivedVarMap) = ([], derivedVarMapUnchecked)
typedDerivedVarMap = unsafeVarMapToTypedVarMap derivedVarMap integerVariables
safelyRoundTypedVarMap [] = []
safelyRoundTypedVarMap ((TypedVar (varName, (leftBound, rightBound)) Real) : vars) =
let
leftBoundRoundedDown = rational . fst . endpoints $ mpBallP (prec 23) leftBound
rightBoundRoundedUp = rational . snd . endpoints $ mpBallP (prec 23) rightBound
newBound = TypedVar (varName, (leftBoundRoundedDown, rightBoundRoundedUp)) Real
in
newBound : safelyRoundTypedVarMap vars
safelyRoundTypedVarMap (vi@(TypedVar _ Integer) : vars) = vi : safelyRoundTypedVarMap vars
simplifiedF = simplifiedFUnchecked
First elem are the variables which can be assumed to be real pi
Second elem is the varMap without the real pi vars
findRealPiVars :: VarMap -> ([String], VarMap)
findRealPiVars [] = ([], [])
findRealPiVars (varWithBounds@(var, (l, r)) : vars) =
if
(var =~ "^pi$|^pi[0-9]+$" :: Bool) &&
l >= (7074237752028440.0 / 2251799813685248.0) && r <= (7074237752028441.0 / 2251799813685248.0) &&
(lookup var varsWithTypes == Just "Real")
then (\(foundPiVars, varMapWithoutPi) -> ((var : foundPiVars), varMapWithoutPi)) $ findRealPiVars vars
else (\(foundPiVars, varMapWithoutPi) -> (foundPiVars, (varWithBounds : varMapWithoutPi))) $ findRealPiVars vars
substVarsWithPi :: [String] -> F -> F
substVarsWithPi [] f = f
substVarsWithPi (v : _) f = substVarFWithE v f Pi
Need to preserve unsat terms , so we can safely remove x in FConn And x y if x contains underivable variables .
We can not safely remove x from FConn Or x y if x contains underivable variables
filterOutVars :: F -> [String] -> Bool -> Maybe F
filterOutVars (FConn And f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn And ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FConn Or f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn Or ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn Impl f1 f2) vars False =
case (filterOutVars f1 vars False, filterOutVars f2 vars False) of
(Just ff1, Just ff2) -> Just $ FConn Impl ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn And f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn And ff1 ff2
(_, _) -> Nothing
filterOutVars (FConn Or f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn Or ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FConn Impl f1 f2) vars True =
case (filterOutVars f1 vars True, filterOutVars f2 vars True) of
(Just ff1, Just ff2) -> Just $ FConn Impl ff1 ff2
(Just ff1, _) -> Just ff1
(_, Just ff2) -> Just ff2
(_, _) -> Nothing
filterOutVars (FNot f) vars isNegated = FNot <$> filterOutVars f vars (not isNegated)
filterOutVars (FComp op e1 e2) vars _isNegated =
if eContainsVars vars e1 || eContainsVars vars e2
then Nothing
else Just (FComp op e1 e2)
filterOutVars FTrue _ _ = Just FTrue
filterOutVars FFalse _ _ = Just FFalse
eContainsVars :: [String] -> E -> Bool
eContainsVars vars (Var var) = var `elem` vars
eContainsVars _ (Lit _) = False
eContainsVars _ Pi = False
eContainsVars vars (EBinOp _ e1 e2) = eContainsVars vars e1 || eContainsVars vars e2
eContainsVars vars (EUnOp _ e) = eContainsVars vars e
eContainsVars vars (PowI e _) = eContainsVars vars e
eContainsVars vars (Float32 _ e) = eContainsVars vars e
eContainsVars vars (Float64 _ e) = eContainsVars vars e
eContainsVars vars (Float _ e) = eContainsVars vars e
eContainsVars vars (RoundToInteger _ e) = eContainsVars vars e
fContainsVars :: [String] -> F -> Bool
fContainsVars vars (FConn _ f1 f2) = fContainsVars vars f1 || fContainsVars vars f2
fContainsVars vars (FComp _ e1 e2) = eContainsVars vars e1 || eContainsVars vars e2
fContainsVars vars (FNot f) = fContainsVars vars f
fContainsVars _ FTrue = False
fContainsVars _ FFalse = False
inequalityEpsilon :: Rational
inequalityEpsilon = 0.000000001
inequalityEpsilon = 1/(2 ^ 23 )
findVarEqualities :: F -> [(String, E)]
findVarEqualities (FConn And f1 f2) = findVarEqualities f1 ++ findVarEqualities f2
findVarEqualities FConn {} = []
findVarEqualities (FComp Eq (Var v) e2) = [(v, e2)]
findVarEqualities (FComp Eq e1 (Var v)) = [(v, e1)]
findVarEqualities FComp {} = []
findVarEqualities FTrue = []
findVarEqualities FFalse = []
filterOutCircularVarEqualities :: [(String, E)] -> [(String, E)]
filterOutCircularVarEqualities = filter (\(v, e) -> v `notElem` findVariablesInExpressions e)
filterOutDuplicateVarEqualities :: [(String, E)] -> [(String, E)]
filterOutDuplicateVarEqualities [] = []
filterOutDuplicateVarEqualities ((v, e) : vs) =
case partition (\(v',_) -> v == v') vs of
([], _) -> (v, e) : filterOutDuplicateVarEqualities vs
(matchingEqualities, otherEqualities) ->
let shortestVarEquality = head $ sortBy (\(_, e1) (_, e2) -> P.compare (lengthE e1) (lengthE e2)) $ (v, e) : matchingEqualities
in shortestVarEquality : filterOutDuplicateVarEqualities otherEqualities
FIXME : subst one at a time
substAllEqualities :: F -> F
substAllEqualities = recursivelySubstVars
where
recursivelySubstVars f@(FConn Impl context _) =
case filteredVarEqualities of
[] -> f
where
substitutedF = substVars filteredVarEqualities f
filteredVarEqualities = (filterOutDuplicateVarEqualities . filterOutCircularVarEqualities) varEqualities
varEqualities = findVarEqualities context
recursivelySubstVars f =
case filteredVarEqualities of
[] -> f
_ -> if f P.== substitutedF then f else recursivelySubstVars . simplifyF $ substitutedF
where
substitutedF = substVars filteredVarEqualities f
filteredVarEqualities = (filterOutDuplicateVarEqualities . filterOutCircularVarEqualities) varEqualities
varEqualities = findVarEqualities f
substVars [] f = f
substVars ((v, e) : _) f = substVarFWithE v f e
addVarMapBoundsToF :: F -> TypedVarMap -> F
addVarMapBoundsToF f [] = f
addVarMapBoundsToF f (TypedVar (v, (l, r)) _ : vm) = FConn And boundAsF $ addVarMapBoundsToF f vm
where
boundAsF = FConn And (FComp Ge (Var v) (Lit l)) (FComp Le (Var v) (Lit r))
eliminateFloatsAndSimplifyVC :: F -> TypedVarMap -> Bool -> FilePath -> IO F
eliminateFloatsAndSimplifyVC vc typedVarMap strengthenVC fptaylorPath =
do
vcWithoutFloats <- eliminateFloatsF vc (typedVarMapToVarMap typedVarMap) strengthenVC fptaylorPath
let typedVarMapAsMap = M.fromList $ map (\(TypedVar (varName, (leftBound, rightBound)) _) -> (varName, (Just leftBound, Just rightBound))) typedVarMap
let simplifiedVCWithoutFloats = (simplifyF . evalF_comparisons typedVarMapAsMap) vcWithoutFloats
return simplifiedVCWithoutFloats
parseVCToF :: FilePath -> FilePath -> IO (Maybe (F, TypedVarMap))
parseVCToF filePath fptaylorPath =
do
parsedFile <- parseSMT2 filePath
case processVC parsedFile of
Just (vc, varTypes) ->
let
simplifiedVC = (symbolicallySubstitutePiVars . substAllEqualities . simplifyF) vc
mDerivedVCWithRanges = deriveVCRanges simplifiedVC varTypes
in
case mDerivedVCWithRanges of
Just (derivedVC, derivedRanges) ->
do
let strengthenVC = False
vcWithoutFloats <- eliminateFloatsF derivedVC (typedVarMapToVarMap derivedRanges) strengthenVC fptaylorPath
let vcWithoutFloatsWithBounds = addVarMapBoundsToF vcWithoutFloats derivedRanges
case deriveVCRanges vcWithoutFloatsWithBounds varTypes of
Just (simplifiedVCWithoutFloats, finalDerivedRanges) -> return $ Just (simplifiedVCWithoutFloats, finalDerivedRanges)
Nothing -> error "Error deriving bounds again after floating-point elimination"
Nothing -> return Nothing
Nothing -> return Nothing
parseVCToSolver :: FilePath -> FilePath -> (F -> TypedVarMap -> String) -> Bool -> IO (Maybe String)
parseVCToSolver filePath fptaylorPath proverTranslator negateVC =
do
parsedFile <- parseSMT2 filePath
case processVC parsedFile of
Just (vc, varTypes) ->
let
simplifiedVC = (substAllEqualities . simplifyF) vc
mDerivedVCWithRanges = deriveVCRanges simplifiedVC varTypes
in
case mDerivedVCWithRanges of
Just (derivedVC, derivedRanges) ->
do
let strengthenVC = False
vcWithoutFloats <- eliminateFloatsF derivedVC (typedVarMapToVarMap derivedRanges) strengthenVC fptaylorPath
let vcWithoutFloatsWithBounds = addVarMapBoundsToF vcWithoutFloats derivedRanges
case deriveVCRanges vcWithoutFloatsWithBounds varTypes of
Just (simplifiedVCWithoutFloats, finalDerivedRanges) ->
return $ Just (
proverTranslator
(
if negateVC
then
case simplifiedVCWithoutFloats of
Eliminate double not
_ -> FNot simplifiedVCWithoutFloats
else simplifiedVCWithoutFloats
)
finalDerivedRanges
)
Nothing -> error "Error deriving bounds again after floating-point elimination"
return $ Just ( proverTranslator ( if negateVC then simplifyF ( FNot simplifiedVCWithoutFloats ) else ) derivedRanges )
Nothing -> return Nothing
Nothing -> return Nothing
|
cfacc590687acda44b3a320f9c197c5a8506ce121a911ec2791030ba178b9e76 | arrdem/oxcart | hello.clj | (ns test.hello)
(defn -main []
(. (. System out)
(println "Hello, World!"))
(. System (exit (int 0))))
| null | https://raw.githubusercontent.com/arrdem/oxcart/38c3247dabe904b3c067385a7d64c5f4f65ccc09/src/bench/clojure/test/hello.clj | clojure | (ns test.hello)
(defn -main []
(. (. System out)
(println "Hello, World!"))
(. System (exit (int 0))))
| |
41eec8a6b1463f00b69a41813ecef5b20f184286344f41f7f76332cc44c4f118 | Opetushallitus/ataru | harkinnanvaraisuus_filter_spec.clj | (ns ataru.applications.harkinnanvaraisuus.harkinnanvaraisuus-filter-spec
(:require [speclj.core :refer [it describe tags should=]]
[ataru.applications.harkinnanvaraisuus.harkinnanvaraisuus-filter :as hf]))
(def harkinnanvaraisuus-only-filters
{:filters {:harkinnanvaraisuus {:only-harkinnanvaraiset true}}})
(def application-data
{"application-1-id"
{:form "form-1-id"
:content {:answers []}}})
(defn- fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
[response]
(fn [_]
response))
(describe "filter-applications-by-harkinnanvaraisuus"
(tags :unit :harkinnanvaraisuus)
(it "returns empty vector when given empty vector"
(let [input []
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta {})
input
harkinnanvaraisuus-only-filters)]
(should= [] result)))
(it "returns all applications if :only-harkinnanvaraiset flag is false"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta {})
input
{:harkinnanvaraisuus {:only-harkinnanvaraiset false}})]
(should= input result)))
(it "does not return application if it has no application-wide reason for harkinnanvaraisuus"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= [] result)))
(it "returns application if it has an application-wide reason for harkinnanvaraisuus"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_ULKOMAILLA_OPISKELTU"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= input result)))
(it "returns application if it has a harkinnanvaraisuus reason for some hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= input result)))
(describe "when filtering by hakukohteet as well"
(it "returns application if it has a harkinnanvaraisuus reason for given hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
(assoc harkinnanvaraisuus-only-filters :selected-hakukohteet #{"hakukohde-oid-1"}))]
(should= input result)))
(it "does not return application if it has a harkinnanvaraisuus reason for another hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
(assoc harkinnanvaraisuus-only-filters :selected-hakukohteet #{"hakukohde-oid-2"}))]
(should= [] result)))))
| null | https://raw.githubusercontent.com/Opetushallitus/ataru/88addd3a5604564ac4d636f4f0321f465ce0a5b7/spec/ataru/applications/harkinnanvaraisuus/harkinnanvaraisuus_filter_spec.clj | clojure | (ns ataru.applications.harkinnanvaraisuus.harkinnanvaraisuus-filter-spec
(:require [speclj.core :refer [it describe tags should=]]
[ataru.applications.harkinnanvaraisuus.harkinnanvaraisuus-filter :as hf]))
(def harkinnanvaraisuus-only-filters
{:filters {:harkinnanvaraisuus {:only-harkinnanvaraiset true}}})
(def application-data
{"application-1-id"
{:form "form-1-id"
:content {:answers []}}})
(defn- fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
[response]
(fn [_]
response))
(describe "filter-applications-by-harkinnanvaraisuus"
(tags :unit :harkinnanvaraisuus)
(it "returns empty vector when given empty vector"
(let [input []
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta {})
input
harkinnanvaraisuus-only-filters)]
(should= [] result)))
(it "returns all applications if :only-harkinnanvaraiset flag is false"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta {})
input
{:harkinnanvaraisuus {:only-harkinnanvaraiset false}})]
(should= input result)))
(it "does not return application if it has no application-wide reason for harkinnanvaraisuus"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= [] result)))
(it "returns application if it has an application-wide reason for harkinnanvaraisuus"
(let [input [{:key "application-1-id"}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_ULKOMAILLA_OPISKELTU"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= input result)))
(it "returns application if it has a harkinnanvaraisuus reason for some hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
harkinnanvaraisuus-only-filters)]
(should= input result)))
(describe "when filtering by hakukohteet as well"
(it "returns application if it has a harkinnanvaraisuus reason for given hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
(assoc harkinnanvaraisuus-only-filters :selected-hakukohteet #{"hakukohde-oid-1"}))]
(should= input result)))
(it "does not return application if it has a harkinnanvaraisuus reason for another hakukohde"
(let [input [{:key "application-1-id" :hakukohde ["hakukohde-oid-1" "hakukohde-oid-2"]}]
result (hf/filter-applications-by-harkinnanvaraisuus
(fake-hakemusten-harkinnanvaraisuus-valintalaskennasta
{"application-1-id"
{:hakemusOid "application-1-id"
:hakutoiveet [{:hakukohdeOid "hakukohde-oid-1"
:harkinnanvaraisuudenSyy "ATARU_SOSIAALISET_SYYT"}
{:hakukohdeOid "hakukohde-oid-2"
:harkinnanvaraisuudenSyy "EI_HARKINNANVARAINEN"}]}})
input
(assoc harkinnanvaraisuus-only-filters :selected-hakukohteet #{"hakukohde-oid-2"}))]
(should= [] result)))))
| |
0558abaa2f6f3faf7741f7db7607bb9ce9288d9c7ffda8f4866a2115509856a5 | microsoft/SLAyer | Graph.ml | Copyright ( c ) Microsoft Corporation . All rights reserved .
(** Mutable edge- and vertex-labelled multi-graphs *)
open Library
module L = (val Log.std Config.vGraph : Log.LOG)
(*============================================================================
Graph
============================================================================*)
include Graph_sig
module Make
(Index: sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val hash: t -> int
val fmt : t formatter
end)
(VertexLabel: sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val fmt : t formatter
end)
(EdgeLabel: sig
type t
val compare: t -> t -> int
val equal : t -> t -> bool
val fmt : t formatter
end)
:
(GRAPH
with type index = Index.t
and type v_label = VertexLabel.t
and type e_label = EdgeLabel.t
)
=
struct
type index = Index.t
type v_label = VertexLabel.t
type e_label = EdgeLabel.t
module EdgeLabelSet = Set.Make(EdgeLabel)
module rec Vertex : sig
(* vertices of graphs are represented by pairs of an index and a
label, and carries the sets of incoming and outgoing edges *)
(* Note: do both incoming and outgoing edges need to be labeled? *)
type label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type t = index * label_n_neighbors
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
val fmt : t formatter
end = struct
type label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type t = index * label_n_neighbors
(* comparison of vertices ignores incoming/outgoing edges *)
let compare (x,{label=j}) (y,{label=k}) =
let c = Index.compare x y in if c <> 0 then c else VertexLabel.compare j k
let equal (x,{label=j}) (y,{label=k}) =
(Index.equal x y) && (VertexLabel.equal j k)
let hash (x,_) =
Index.hash x
let fmt ff (i,{label}) =
Format.fprintf ff "@[%a:@ %a@]" Index.fmt i VertexLabel.fmt label
end
(* sets of edges to/from neighbors are represented as multi-maps from
vertices (to edge labels) *)
and VertexMMap : (ImperativeMultiMap.S
with type k = Vertex.t
and type v = EdgeLabel.t
and type vs = EdgeLabelSet.t)
= ImperativeMultiMap.Make (Vertex) (EdgeLabelSet)
module VertexISet = ImperativeSet.Make(Vertex)
module VertexSet = Set.Make(Vertex)
module VertexIMap = ImperativeMap.Make(Vertex)
module VertexMap = Map.Make(Vertex)
type label_n_neighbors = Vertex.label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type vertex = index * label_n_neighbors
module IndexLabelSet =
ImperativeSet.Make
(struct
type t = index * v_label
let equal = equal_tup2 Index.equal VertexLabel.equal
let compare = compare_tup2 Index.compare VertexLabel.compare
end)
type roots = IndexLabelSet.t
(* graphs are represented by sets of vertices, which are implemented
using the isomorphic domain of multi-maps from indices to sets of
label-and-neighbor tuples, which are implemented using maps from
labels to pairs of edge sets *)
module SubVertex = ImperativeMap.Make(VertexLabel)
module Vertices = HashMap.Make(Index)
type rays = VertexMMap.t
type graph = {
verts: ((rays * rays) SubVertex.t) Vertices.t;
roots: roots
}
let create () = {verts= Vertices.create 31; roots= IndexLabelSet.create ()}
let clear g = Vertices.clear g.verts ; IndexLabelSet.clear g.roots
let index_of v = fst v
let label_of v = (snd v).label
let in_degree v = VertexMMap.length (snd v).incoming
let out_degree v = VertexMMap.length (snd v).outgoing
let iter_preds fn v = VertexMMap.iter fn (snd v).incoming
let iter_succs fn v = VertexMMap.iter fn (snd v).outgoing
let fold_preds fn v = VertexMMap.fold fn (snd v).incoming
let fold_succs fn v = VertexMMap.fold fn (snd v).outgoing
let predecessors v = fold_preds (fun v e r -> (v,e)::r) v []
let successors v = fold_succs (fun v e r -> (v,e)::r) v []
let vertices_for g k =
match Vertices.tryfind g.verts k with
| None ->
[]
| Some(vs) ->
SubVertex.fold (fun label (incoming, outgoing) a ->
(k, {label; incoming; outgoing}) :: a
) vs []
let roots g =
IndexLabelSet.fold (fun (k,l) roots ->
List.fold (fun ((_,{label}) as v) roots ->
if VertexLabel.equal l label then
v :: roots
else
roots
) (vertices_for g k) roots
) g.roots []
let mem_vertex g (k,{label=l} as v) =
L.printf 2 "mem_vertex: %a" Vertex.fmt v
;
match Vertices.tryfind g.verts k with
| None -> false
| Some(vs) -> SubVertex.mem vs l
let mem_edge g src label trg =
L.printf 2 "mem_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_vertex g src) ;
assert(mem_vertex g trg)
;
let eq_label = EdgeLabel.equal label
in
VertexMMap.existsi trg eq_label (snd src).outgoing
&& VertexMMap.existsi src eq_label (snd trg).incoming
let add_edge g src label trg =
L.printf 1 "add_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label
;
if mem_vertex g src && mem_vertex g trg && not (mem_edge g src label trg)
then (
VertexMMap.add (snd src).outgoing trg label ;
VertexMMap.add (snd trg).incoming src label
)
let remove_edge g src label trg =
L.printf 1 "remove_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert( mem_edge g src label trg ); (fun () -> assert( not (mem_edge g src label trg) )) <&
let eq_label lbl = not (EdgeLabel.equal label lbl)
in
VertexMMap.filteri trg eq_label (snd src).outgoing ;
VertexMMap.filteri src eq_label (snd trg).incoming
let add_vertex g (k,l) =
let do_add vs =
let v =
{label= l; incoming= VertexMMap.create(); outgoing= VertexMMap.create()}
in
L.printf 1 "add_vertex: %a" Vertex.fmt (k,v) ;
SubVertex.add vs v.label (v.incoming, v.outgoing) ;
(k,v)
in
match Vertices.tryfind g.verts k with
| None ->
let vs = SubVertex.create () in
Vertices.add g.verts k vs ;
do_add vs
| Some(vs) ->
match SubVertex.tryfind vs l with
| None ->
do_add vs
| Some((i,o)) ->
L.printf 1 "add_vertex: already exists: %a: %a" Index.fmt k VertexLabel.fmt l ;
(k, {label= l; incoming= i; outgoing= o})
let rec remove_vertex g ((k, {label= l; incoming= i; outgoing= o}) as v) =
L.incf 1 "( remove_vertex: %a" Vertex.fmt v ;
(fun _ -> L.decf 1 ") remove_vertex")
<&
if mem_vertex g v
&& VertexMMap.is_empty i
&& not (IndexLabelSet.mem g.roots (k,l))
then (
L.printf 1 "vertex is unreachable and not a root"
;
VertexMMap.iter (fun u l -> remove_edge g v l u ; remove_vertex g u) o
;
match Vertices.tryfind g.verts k with
| None -> ()
| Some(vs) ->
SubVertex.remove vs l ;
if SubVertex.is_empty vs then Vertices.remove g.verts k
)
let replace_vertex g new_label old_trg new_trg =
L.incf 1 "( replace_vertex: %a with %a" Vertex.fmt old_trg Vertex.fmt new_trg ;
(fun _ -> L.decf 1 ") replace_vertex")
<&
let swing_edge g src label old_trg new_trg =
if mem_edge g src label old_trg then (
remove_edge g src label old_trg ;
add_edge g src (new_label label) new_trg
)
in
assert( not (Vertex.equal old_trg new_trg) );
VertexMMap.iter (fun src lab ->
swing_edge g src lab old_trg new_trg
) (snd old_trg).incoming ;
assert( VertexMMap.is_empty (snd old_trg).incoming );
VertexMMap.iter (fun succ lab ->
add_edge g new_trg (new_label lab) (if Vertex.equal succ old_trg then new_trg else succ)
) (snd old_trg).outgoing ;
assert( VertexMMap.is_empty (snd old_trg).incoming );
remove_vertex g old_trg
let relabel_vertex g ((k,{label}) as old_vtx) new_label =
assert( VertexLabel.equal label new_label
|| invalid_arg "relabel_vertex must preserve equality of labels" );
assert( mem_vertex g old_vtx
|| invalid_arg "relabel_vertex must relabel existing vertex" );
let vs = Vertices.find g.verts k in
let i,o = SubVertex.find vs label in
let new_vtx = (k, {label= new_label; incoming= i; outgoing= o}) in
VertexMMap.iter (fun v l ->
remove_edge g v l old_vtx ;
add_edge g v l new_vtx
) i ;
SubVertex.add vs new_label (i,o) ;
new_vtx
let collapse_edge_pre g src label trg =
L.printf 1 "collapse_edge_pre: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_edge g src label trg)
;
remove_edge g src label trg
;
VertexMMap.iter (fun u l ->
remove_edge g u l trg ;
add_edge g (if Vertex.equal u trg then src else u) l src
) (snd trg).incoming
;
VertexMMap.iter (fun u l ->
remove_edge g trg l u ;
add_edge g src l (if Vertex.equal u trg then src else u)
) (snd trg).outgoing
;
remove_vertex g trg
let collapse_edge_post g src label trg =
L.printf 1 "collapse_edge_post: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_edge g src label trg)
;
VertexMMap.iter (fun u l ->
remove_edge g u l src ;
add_edge g (if Vertex.equal u src then trg else u) l trg
) (snd src).incoming
;
remove_edge g src label trg ;
remove_vertex g src
let root_vertex g (k,a) =
IndexLabelSet.add g.roots (k,a.label)
let unroot_vertex g (k,a) =
IndexLabelSet.remove g.roots (k,a.label)
let fold_vertices_index fn g k z =
match Vertices.tryfind g.verts k with
| None ->
z
| Some(vs) ->
SubVertex.fold (fun label (incoming,outgoing) z ->
let v = (k, {label; incoming; outgoing}) in
if mem_vertex g v
then fn v z
else z
) vs z
let iter_vertices_index fn g k =
fold_vertices_index (fun v () -> fn v) g k ()
let fold_vertices fn g z =
Vertices.fold
(fun k vs z ->
SubVertex.fold
(fun l (i,o) a ->
let v = (k, {label=l; incoming=i; outgoing=o}) in
fn v a
) vs z
) g.verts z
let iter_vertices fn g =
fold_vertices (fun v () -> fn v) g ()
let fold_edges vertex_fn edge_fn g k z =
let edge_opt_fn prev_opt curr z =
match prev_opt with
| Some(prev,label) -> edge_fn (prev,label,curr) z
| None -> z
in
let memo = VertexISet.create ()
in
let rec walk prev_opt curr z =
if VertexISet.mem memo curr then
edge_opt_fn prev_opt curr z
else
let z = vertex_fn curr z in
let z = edge_opt_fn prev_opt curr z in
VertexISet.add memo curr ;
VertexMMap.fold (fun next label z ->
walk (Some(curr,label)) next z
) (snd curr).outgoing z
in
fold_vertices_index (walk None) g k z
let iter_edges vertex_fn edge_fn g k =
fold_edges (fun v () -> vertex_fn v) (fun e () -> edge_fn e) g k ()
let identify_vertices g =
let vertex_ids : int VertexIMap.t = VertexIMap.create () in
let count = ref 0 in
let identify_vertex v =
if not (VertexIMap.mem vertex_ids v) then (
VertexIMap.add vertex_ids v !count ;
incr count
)
in
iter_vertices identify_vertex g ;
vertex_ids
let cutpoints root =
let rec df_walk src ancestors visited cutpoints =
VertexMMap.fold (fun trg _ (visited, cutpoints) ->
if not (VertexSet.mem trg visited) then
df_walk trg (VertexSet.add trg ancestors) (VertexSet.add trg visited) cutpoints
else if not (VertexSet.mem trg ancestors) then
(visited, cutpoints)
else
(visited, VertexSet.add trg cutpoints)
) (snd src).outgoing (visited, cutpoints)
in
let roots = VertexSet.singleton root
in
snd (df_walk root roots roots VertexSet.empty)
Breadth - first search from CLR Algorithms textbook .
type visit_state = White | Grey | Black
let bfs g start =
State
let colour : visit_state VertexIMap.t = VertexIMap.create () in
let distance : int VertexIMap.t = VertexIMap.create () in
let predecessor : (vertex * e_label) option VertexIMap.t =
VertexIMap.create () in
let grey_q : vertex Queue.t = Queue.create () in
Initialize state .
iter_vertices
(fun v ->
VertexIMap.add colour v White ;
VertexIMap.add distance v max_int ;
VertexIMap.add predecessor v None
)
g ;
VertexIMap.add colour start Grey ;
VertexIMap.add distance start 0 ;
VertexIMap.add predecessor start None ;
Queue.push start grey_q;
(* Main loop. *)
while (not (Queue.is_empty grey_q)) do
L.incf 2 "( bfs visit" ; (fun _ -> L.decf 2 ") bfs visit") <&
let u = Queue.peek grey_q in
L.printf 2 " u --> v, where@\nu is %a" Vertex.fmt u ;
List.iter (fun (v,tr) ->
L.printf 2 " v is %a" Vertex.fmt v ;
if (VertexIMap.find colour v = White) then (
L.printf 2 " v is White" ;
VertexIMap.add colour v Grey ;
VertexIMap.add distance v ((VertexIMap.find distance u) + 1) ;
VertexIMap.add predecessor v (Some (u,tr)) ;
Queue.push v grey_q
) else
L.printf 2 " v is not White" ;
) (successors u) ;
let _ = Queue.pop grey_q in
VertexIMap.add colour u Black
done ;
(distance,predecessor)
(* Depth-first search *)
let dfs_iter ?next:(next=fun () -> () ) ?forwards:(forwards=true) pre post starts =
let visited = VertexISet.create ()
in
let rec dfs_visit u =
L.incf 1 "( dfs visit: u is %a" Vertex.fmt u ; (fun _ -> L.decf 1 ") dfs visit") <&
if not (VertexISet.mem visited u) then (
VertexISet.add visited u ;
pre u ;
VertexMMap.iter (fun v _ ->
dfs_visit v
) (if forwards then (snd u).outgoing else (snd u).incoming) ;
post u
)
in
List.iter (fun start -> dfs_visit start ; next()) starts
Implementation from Introduction to Algorithms , Cormen et al
Section 23.5 Page 488
Section 23.5 Page 488
*)
let scc graph =
(fun scc_map -> assert(true$>
if Config.check_scc then (
let reaches x y =
let res = ref false in
dfs_iter (fun v -> if Vertex.equal v y then res := true) (fun _ -> ()) [x] ;
!res in
iter_vertices (fun x ->
iter_vertices (fun y ->
if not (Vertex.equal x y) then
let scc_x = VertexMap.find x scc_map in
let scc_y = VertexMap.find y scc_map in
if (scc_x == scc_y) <> (reaches x y && reaches y x) then
failwith "Graph.scc incorrect"
) graph
) graph
)
))<&
let vtxs = fold_vertices List.cons graph [] in
let rev_postorder = ref [] in
let skip = fun _ -> () in
let add_to rl = fun v -> rl := v :: !rl in
(* Get the finished times for each node *)
dfs_iter skip
(add_to rev_postorder)
vtxs ;
(* Walk backwards in reverse finished time *)
let current_scc = ref [] in
let scc_map = ref VertexMap.empty in
dfs_iter ~forwards:false
~next:(fun () ->
Add each vertex in the scc to the map , with the whole SCC
List.iter
(fun v ->
scc_map := VertexMap.add v !current_scc !scc_map
)
(!current_scc) ;
(* Setup next scc *)
current_scc := []
)
skip
(add_to current_scc)
!rev_postorder ;
!scc_map
let dfs start =
let rev_preorder : (vertex list) ref = ref [] in
let rev_postorder : (vertex list) ref = ref [] in
let preorder_map : int VertexIMap.t = VertexIMap.create () in
let postorder_map : int VertexIMap.t = VertexIMap.create () in
let preorder_count = ref 0 in
let postorder_count = ref 0 in
dfs_iter
(fun u ->
rev_preorder := u :: !rev_preorder ;
VertexIMap.add preorder_map u !preorder_count ;
incr preorder_count
)
(fun u ->
rev_postorder := u :: !rev_postorder ;
VertexIMap.add postorder_map u !postorder_count ;
incr postorder_count
)
[start] ;
let preorder = List.rev (!rev_preorder) in
let postorder = List.rev (!rev_postorder) in
let preorder_num = VertexIMap.find preorder_map in
let postorder_num = VertexIMap.find postorder_map in
(preorder, postorder, preorder_num, postorder_num)
let dfs_revpost start =
let rev_postorder = ref [] in
let postorder_map = VertexIMap.create () in
let postorder_count = ref 0 in
dfs_iter (fun _ -> ()) (fun u ->
rev_postorder := u :: !rev_postorder ;
VertexIMap.add postorder_map u !postorder_count ;
incr postorder_count
) [start] ;
(!rev_postorder, VertexIMap.find postorder_map)
Dominance , based on " A Simple , Fast Dominance Algorithm " ( Cooper et al )
let immediate_dominators start =
let rev_postorder, postorder_num = dfs_revpost start in
let nnodes = (postorder_num (List.hd rev_postorder)) + 1 in
let undefined = -1 in
let doms = Array.create nnodes undefined in
doms.(postorder_num start) <- postorder_num start
;
let intersect i j =
let rec outer i j =
if i <> j then
let rec inner i j =
if i < j then
inner doms.(i) j
else
i
in
let i = inner i j in
let j = inner j i in
outer i j
else
i
in
outer i j
in
let not_root = List.tl rev_postorder
in
let rec build_dom_tree progress =
if progress then build_dom_tree (
List.fold (fun n progress ->
let preds = fold_preds (fun p _ preds -> postorder_num p :: preds) n [] in
let processed_pred, other_preds = List.take (fun p -> doms.(p) <> undefined) preds in
let new_idom =
List.fold (fun p new_idom ->
if doms.(p) <> undefined then
intersect p new_idom
else
new_idom
) other_preds processed_pred in
let b = postorder_num n in
if doms.(b) <> new_idom then (
doms.(b) <- new_idom ;
true
) else
progress
) not_root false
)
in
build_dom_tree true
;
(doms, rev_postorder, postorder_num)
(* v dominates u if v is the least-common ancestor of v and u *)
let dominates doms postorder_num v u =
let i = postorder_num v
in
let rec loop j =
if j < i then
loop doms.(j)
else
j = i
in
loop (postorder_num u)
let dominance_frontier cfg start =
let doms, rev_postorder, postorder_num = immediate_dominators start in
let postorder = List.rev rev_postorder in
(* the ith vertex in the postorder traversal *)
let postorder_vtx i =
List.nth postorder i
in
let dfset : VertexISet.t VertexIMap.t = VertexIMap.create () in
iter_vertices
(fun n ->
VertexIMap.add dfset n (VertexISet.create ())
)
cfg;
iter_vertices
(fun n ->
let preds = predecessors n in
if List.length preds >= 2 then (
let b = postorder_num n in
List.iter
(fun (p,_) ->
let runner = ref (postorder_num p) in
while (!runner <> doms.(b)) do
let runner_dfset = VertexIMap.find dfset (postorder_vtx !runner) in
VertexISet.add runner_dfset n;
runner := doms.(!runner)
done
)
preds
)
)
cfg;
(* returns the immediate dominator of n *)
let parent_of n =
try Some(postorder_vtx doms.(postorder_num n))
with Not_found -> None
in
(* returns the set of vertices immediately dominated by n *)
let children_of =
let map : VertexISet.t VertexIMap.t = VertexIMap.create () in
iter_vertices (fun n -> VertexIMap.add map n (VertexISet.create ())) cfg ;
iter_vertices (fun n ->
Option.iter (fun p ->
Option.iter (fun p ->
VertexISet.add p n
) (VertexIMap.tryfind map p)
) (parent_of n)
) cfg ;
VertexISet.remove (VertexIMap.find map start) start;
VertexIMap.find map
in
(* return dominator frontier set,
dominator relation, and
dominator tree functions *)
(dfset, dominates doms postorder_num, parent_of, children_of)
(* Return the set of natural loops in [cfg] with [dominates] relation *)
let natural_loops cfg dominates =
n - > h(eader ) is a backedge if h dominates n
let backedges = fold_vertices
(fun n acc ->
let hs = List.filter
(fun (h,_) -> dominates h n)
(successors n)
in
acc @ (List.map (fun (h,_) -> (h,n)) hs)
)
cfg []
in
(* for each h,n pair, walk up the graph to gather the body *)
List.map
(fun (h,n) ->
let body = VertexISet.create () in
let s = Stack.create () in
VertexISet.add body h;
Stack.push n s;
while (not (Stack.is_empty s)) do
let d = Stack.pop s in
if (not (VertexISet.mem body d)) then (
VertexISet.add body d;
List.iter
(fun (p,_) -> Stack.push p s)
(predecessors d)
)
done;
(body,h,n)
)
backedges
Floyd - Warshall , and construct shortest - path .
From CLR Algorithms textbook .
From CLR Algorithms textbook. *)
type distance = Infinity | D of int
type pre = Nil | P of int
let is_infinity d = match d with Infinity -> true | _ -> false
(* d + d' *)
let add d d' =
match d, d' with
| Infinity,_ | _,Infinity -> Infinity
| D(i), D(i') -> D(i+i')
(* d <= d' *)
let leq d d' =
match d, d' with
| Infinity, _ -> false
| _, Infinity -> true
| D(i), D(i') -> i <= i'
(* SI: should return only in terms of
d : VM.key -> VM.key -> int
pre: VM.key -> VM.key -> int *)
let fw g =
let vtx_to_i = identify_vertices g in
let n = (VertexIMap.fold (fun _vtx i size -> max i size) vtx_to_i 0) + 1 in
(* reverse vtx_to_i *)
let i_to_vtx = IntHMap.create n in
VertexIMap.iter (fun vtx i ->
IntHMap.add i_to_vtx i vtx
) vtx_to_i
;
Is there an edge between the vertex indexed by i
and the one indexed by j ?
and the one indexed by j?*)
let edge i j =
List.exists (fun i' ->
Vertex.equal i' (IntHMap.find i_to_vtx j)
) (List.map fst (successors (IntHMap.find i_to_vtx i)))
in
(* Matrix d (pre) uses None for infinity (NIL). *)
let d = Array.make_matrix n n Infinity in
let pre = Array.make_matrix n n Nil in
(* initialize d *)
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (i=j) then d.(i).(j) <- D(0)
else if (i <> j) then
if (edge i j) then d.(i).(j) <- D(1)
else d.(i).(j) <- Infinity
done
done
;
(* initialize pre *)
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (i=j || (is_infinity d.(i).(j))) then
pre.(i).(j) <- Nil
else
pre.(i).(j) <- P(i)
done
done
;
(* main loop *)
for k = 0 to (n-1) do
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (leq (d.(i).(j)) (add d.(i).(k) d.(k).(j))) then (
(* SI: un-necessary *)
d.(i).(j) <- d.(i).(j) ;
pre.(i).(j) <- pre.(i).(j) ;
) else (
d.(i).(j) <- add d.(i).(k) d.(k).(j) ;
pre.(i).(j) <- pre.(k).(j) ;
)
done
done
done
;
Convert [ d ] and [ pre ] matrices into ( sparse ) Vtx->Vtx->data maps .
let d' = Array.make_matrix n n None in
let pre' = Array.make_matrix n n None in
for i = 0 to (n-1) do
for j = 0 to (n-1) do
d'.(i).(j) <- (match d.(i).(j) with
| D(d) -> Some d
| Infinity -> None );
pre'.(i).(j) <- (match pre.(i).(j) with
| P(p) -> Some p
| Nil -> None )
done
done
;
(* return both [d] and [pre] matrices *)
(vtx_to_i,i_to_vtx, d',pre')
let remove_unreachable g =
(fun () -> assert(true$>
let reachable = VertexISet.create () in
IndexLabelSet.iter (fun (k,label) ->
let incoming, outgoing = SubVertex.find (Vertices.find g.verts k) label in
let r = (k, {label; incoming; outgoing}) in
dfs_iter (fun v ->
VertexISet.add reachable v
) (fun _ -> ()) [r]
) g.roots ;
iter_vertices (fun v ->
assert( VertexISet.mem reachable v
|| L.warnf "remove_unreachable failed to remove: %a" Vertex.fmt v )
) g
)) <&
iter_vertices (remove_vertex g) g
let copy g0 src =
let g = create ()
in
let m =
fold_edges
(fun v m ->
VertexMap.add v (add_vertex g (index_of v, label_of v)) m
)
(fun (u,l,v) m ->
match VertexMap.tryfind u m, VertexMap.tryfind v m with
| Some(u'), Some(v') ->
add_edge g u' l v'; m
| _ ->
m
)
g0
(index_of src)
VertexMap.empty
in
(m, g)
let slice src trg g0 =
let vtx_to_id,_, distance,_ = fw g0
in
let trg_id = VertexIMap.find vtx_to_id trg
in
let g = create ()
in
let m =
fold_edges
(fun v m ->
assert( distance.(VertexIMap.find vtx_to_id src).(VertexIMap.find vtx_to_id v) <> None );
if distance.(VertexIMap.find vtx_to_id v).(trg_id) <> None then
VertexMap.add v (add_vertex g (index_of v, label_of v)) m
else
m
)
(fun (u,l,v) m ->
match VertexMap.tryfind u m, VertexMap.tryfind v m with
| Some(u'), Some(v') ->
add_edge g u' l v'; m
| _ ->
m
)
g0
(index_of src)
VertexMap.empty
in
(m, g)
(* Conversion to dot format. *)
let calculate_margin len =
let rec loop height width =
if width /. height > Config.margin_frac then
loop (height +. 1.) (width /. 2.)
else
int_of_float width
in
if len <= 40 then 40 else
loop 1. (float_of_int len)
let reprint msg =
let src_buf = Buffer.create 128 in
let ff = Format.formatter_of_buffer src_buf in
Format.pp_set_margin ff max_int ;
msg ff ;
Format.pp_print_flush ff () ;
let len = Buffer.length src_buf in
let src_buf = Buffer.create len in
let ff = Format.formatter_of_buffer src_buf in
Format.pp_set_margin ff (calculate_margin len) ;
msg ff ;
Format.pp_print_flush ff () ;
let dst_buf = Buffer.create len in
for ind = 0 to Buffer.length src_buf - 1 do
match Buffer.nth src_buf ind with
| '\n' -> Buffer.add_string dst_buf "\\l"
| '\\' -> Buffer.add_string dst_buf "\\\\"
| '\"' -> Buffer.add_string dst_buf "\\\""
| char -> Buffer.add_char dst_buf char
done ;
Buffer.contents dst_buf
let writers g out =
let id =
let m = identify_vertices g in
VertexIMap.find m
in
let write_vertex v =
let msg v = reprint (fun ff -> Vertex.fmt ff v) in
Printf.bprintf out "%i [shape=box,label=\"v %i: %s\\l\"]\n" (id v) (id v) (msg v)
in
let write_edge (src,lab,trg) =
let msg lab = reprint (fun ff -> EdgeLabel.fmt ff lab) in
Printf.bprintf out "%i -> %i [label=\"%s\\l\"]\n" (id src) (id trg) (msg lab)
in
(write_vertex, write_edge, id)
let write_dot_header out =
Printf.bprintf out "digraph g {\n" ;
if Config.font <> "" then (
Printf.bprintf out "graph [fontname=\"%s\"]\n" Config.font ;
Printf.bprintf out "node [fontname=\"%s\"]\n" Config.font ;
Printf.bprintf out "edge [fontname=\"%s\"]\n" Config.font ;
)
let write_dot_footer out =
Printf.bprintf out "}\n"
(* cfg with dominator tree *)
let cfg_write_dot cfg children_of k out =
let write_vertex, write_edge, id = writers cfg out in
write_dot_header out ;
iter_edges write_vertex write_edge cfg k ;
(* dominator tree edges *)
iter_vertices (fun n ->
VertexISet.iter (fun m ->
Printf.bprintf out "%i -> %i [dir=none, weight=3, penwidth=3, color=\"#660000\"]\n" (id n) (id m))
(children_of n);
) cfg;
write_dot_footer out
let write_dot g k out =
let write_vertex, write_edge, _ = writers g out
in
write_dot_header out ;
iter_edges write_vertex write_edge g k ;
write_dot_footer out
let write_dot_partitioned fn g roots out =
let write_vertex, write_edge, _ = writers g out
in
let vs = ref [] in
List.iter (iter_edges (fun v -> vs := v :: !vs) (fun _ -> ()) g) roots ;
let partitions =
List.classify (fun x y ->
Option.equal (fun a b -> fst a = fst b)
(fn (index_of x)) (fn (index_of y))
) !vs in
write_dot_header out ;
List.iter (fun vs ->
match fn (index_of (List.hd vs)) with
| None -> ()
| Some(name,msg) ->
Printf.bprintf out "subgraph cluster%s {\nlabel=\"%s\"\n" name (reprint msg) ;
List.iter write_vertex vs ;
Printf.bprintf out "}\n"
) partitions ;
List.iter (fun root ->
iter_edges
(fun v ->
match fn (index_of v) with
| Some _ -> ()
| None -> write_vertex v
)
write_edge
g root
) roots ;
write_dot_footer out
end
| null | https://raw.githubusercontent.com/microsoft/SLAyer/6f46f6999c18f415bc368b43b5ba3eb54f0b1c04/src/Graph.ml | ocaml | * Mutable edge- and vertex-labelled multi-graphs
============================================================================
Graph
============================================================================
vertices of graphs are represented by pairs of an index and a
label, and carries the sets of incoming and outgoing edges
Note: do both incoming and outgoing edges need to be labeled?
comparison of vertices ignores incoming/outgoing edges
sets of edges to/from neighbors are represented as multi-maps from
vertices (to edge labels)
graphs are represented by sets of vertices, which are implemented
using the isomorphic domain of multi-maps from indices to sets of
label-and-neighbor tuples, which are implemented using maps from
labels to pairs of edge sets
Main loop.
Depth-first search
Get the finished times for each node
Walk backwards in reverse finished time
Setup next scc
v dominates u if v is the least-common ancestor of v and u
the ith vertex in the postorder traversal
returns the immediate dominator of n
returns the set of vertices immediately dominated by n
return dominator frontier set,
dominator relation, and
dominator tree functions
Return the set of natural loops in [cfg] with [dominates] relation
for each h,n pair, walk up the graph to gather the body
d + d'
d <= d'
SI: should return only in terms of
d : VM.key -> VM.key -> int
pre: VM.key -> VM.key -> int
reverse vtx_to_i
Matrix d (pre) uses None for infinity (NIL).
initialize d
initialize pre
main loop
SI: un-necessary
return both [d] and [pre] matrices
Conversion to dot format.
cfg with dominator tree
dominator tree edges | Copyright ( c ) Microsoft Corporation . All rights reserved .
open Library
module L = (val Log.std Config.vGraph : Log.LOG)
include Graph_sig
module Make
(Index: sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val hash: t -> int
val fmt : t formatter
end)
(VertexLabel: sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val fmt : t formatter
end)
(EdgeLabel: sig
type t
val compare: t -> t -> int
val equal : t -> t -> bool
val fmt : t formatter
end)
:
(GRAPH
with type index = Index.t
and type v_label = VertexLabel.t
and type e_label = EdgeLabel.t
)
=
struct
type index = Index.t
type v_label = VertexLabel.t
type e_label = EdgeLabel.t
module EdgeLabelSet = Set.Make(EdgeLabel)
module rec Vertex : sig
type label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type t = index * label_n_neighbors
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
val fmt : t formatter
end = struct
type label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type t = index * label_n_neighbors
let compare (x,{label=j}) (y,{label=k}) =
let c = Index.compare x y in if c <> 0 then c else VertexLabel.compare j k
let equal (x,{label=j}) (y,{label=k}) =
(Index.equal x y) && (VertexLabel.equal j k)
let hash (x,_) =
Index.hash x
let fmt ff (i,{label}) =
Format.fprintf ff "@[%a:@ %a@]" Index.fmt i VertexLabel.fmt label
end
and VertexMMap : (ImperativeMultiMap.S
with type k = Vertex.t
and type v = EdgeLabel.t
and type vs = EdgeLabelSet.t)
= ImperativeMultiMap.Make (Vertex) (EdgeLabelSet)
module VertexISet = ImperativeSet.Make(Vertex)
module VertexSet = Set.Make(Vertex)
module VertexIMap = ImperativeMap.Make(Vertex)
module VertexMap = Map.Make(Vertex)
type label_n_neighbors = Vertex.label_n_neighbors = {
label: v_label;
incoming: VertexMMap.t;
outgoing: VertexMMap.t;
}
type vertex = index * label_n_neighbors
module IndexLabelSet =
ImperativeSet.Make
(struct
type t = index * v_label
let equal = equal_tup2 Index.equal VertexLabel.equal
let compare = compare_tup2 Index.compare VertexLabel.compare
end)
type roots = IndexLabelSet.t
module SubVertex = ImperativeMap.Make(VertexLabel)
module Vertices = HashMap.Make(Index)
type rays = VertexMMap.t
type graph = {
verts: ((rays * rays) SubVertex.t) Vertices.t;
roots: roots
}
let create () = {verts= Vertices.create 31; roots= IndexLabelSet.create ()}
let clear g = Vertices.clear g.verts ; IndexLabelSet.clear g.roots
let index_of v = fst v
let label_of v = (snd v).label
let in_degree v = VertexMMap.length (snd v).incoming
let out_degree v = VertexMMap.length (snd v).outgoing
let iter_preds fn v = VertexMMap.iter fn (snd v).incoming
let iter_succs fn v = VertexMMap.iter fn (snd v).outgoing
let fold_preds fn v = VertexMMap.fold fn (snd v).incoming
let fold_succs fn v = VertexMMap.fold fn (snd v).outgoing
let predecessors v = fold_preds (fun v e r -> (v,e)::r) v []
let successors v = fold_succs (fun v e r -> (v,e)::r) v []
let vertices_for g k =
match Vertices.tryfind g.verts k with
| None ->
[]
| Some(vs) ->
SubVertex.fold (fun label (incoming, outgoing) a ->
(k, {label; incoming; outgoing}) :: a
) vs []
let roots g =
IndexLabelSet.fold (fun (k,l) roots ->
List.fold (fun ((_,{label}) as v) roots ->
if VertexLabel.equal l label then
v :: roots
else
roots
) (vertices_for g k) roots
) g.roots []
let mem_vertex g (k,{label=l} as v) =
L.printf 2 "mem_vertex: %a" Vertex.fmt v
;
match Vertices.tryfind g.verts k with
| None -> false
| Some(vs) -> SubVertex.mem vs l
let mem_edge g src label trg =
L.printf 2 "mem_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_vertex g src) ;
assert(mem_vertex g trg)
;
let eq_label = EdgeLabel.equal label
in
VertexMMap.existsi trg eq_label (snd src).outgoing
&& VertexMMap.existsi src eq_label (snd trg).incoming
let add_edge g src label trg =
L.printf 1 "add_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label
;
if mem_vertex g src && mem_vertex g trg && not (mem_edge g src label trg)
then (
VertexMMap.add (snd src).outgoing trg label ;
VertexMMap.add (snd trg).incoming src label
)
let remove_edge g src label trg =
L.printf 1 "remove_edge: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert( mem_edge g src label trg ); (fun () -> assert( not (mem_edge g src label trg) )) <&
let eq_label lbl = not (EdgeLabel.equal label lbl)
in
VertexMMap.filteri trg eq_label (snd src).outgoing ;
VertexMMap.filteri src eq_label (snd trg).incoming
let add_vertex g (k,l) =
let do_add vs =
let v =
{label= l; incoming= VertexMMap.create(); outgoing= VertexMMap.create()}
in
L.printf 1 "add_vertex: %a" Vertex.fmt (k,v) ;
SubVertex.add vs v.label (v.incoming, v.outgoing) ;
(k,v)
in
match Vertices.tryfind g.verts k with
| None ->
let vs = SubVertex.create () in
Vertices.add g.verts k vs ;
do_add vs
| Some(vs) ->
match SubVertex.tryfind vs l with
| None ->
do_add vs
| Some((i,o)) ->
L.printf 1 "add_vertex: already exists: %a: %a" Index.fmt k VertexLabel.fmt l ;
(k, {label= l; incoming= i; outgoing= o})
let rec remove_vertex g ((k, {label= l; incoming= i; outgoing= o}) as v) =
L.incf 1 "( remove_vertex: %a" Vertex.fmt v ;
(fun _ -> L.decf 1 ") remove_vertex")
<&
if mem_vertex g v
&& VertexMMap.is_empty i
&& not (IndexLabelSet.mem g.roots (k,l))
then (
L.printf 1 "vertex is unreachable and not a root"
;
VertexMMap.iter (fun u l -> remove_edge g v l u ; remove_vertex g u) o
;
match Vertices.tryfind g.verts k with
| None -> ()
| Some(vs) ->
SubVertex.remove vs l ;
if SubVertex.is_empty vs then Vertices.remove g.verts k
)
let replace_vertex g new_label old_trg new_trg =
L.incf 1 "( replace_vertex: %a with %a" Vertex.fmt old_trg Vertex.fmt new_trg ;
(fun _ -> L.decf 1 ") replace_vertex")
<&
let swing_edge g src label old_trg new_trg =
if mem_edge g src label old_trg then (
remove_edge g src label old_trg ;
add_edge g src (new_label label) new_trg
)
in
assert( not (Vertex.equal old_trg new_trg) );
VertexMMap.iter (fun src lab ->
swing_edge g src lab old_trg new_trg
) (snd old_trg).incoming ;
assert( VertexMMap.is_empty (snd old_trg).incoming );
VertexMMap.iter (fun succ lab ->
add_edge g new_trg (new_label lab) (if Vertex.equal succ old_trg then new_trg else succ)
) (snd old_trg).outgoing ;
assert( VertexMMap.is_empty (snd old_trg).incoming );
remove_vertex g old_trg
let relabel_vertex g ((k,{label}) as old_vtx) new_label =
assert( VertexLabel.equal label new_label
|| invalid_arg "relabel_vertex must preserve equality of labels" );
assert( mem_vertex g old_vtx
|| invalid_arg "relabel_vertex must relabel existing vertex" );
let vs = Vertices.find g.verts k in
let i,o = SubVertex.find vs label in
let new_vtx = (k, {label= new_label; incoming= i; outgoing= o}) in
VertexMMap.iter (fun v l ->
remove_edge g v l old_vtx ;
add_edge g v l new_vtx
) i ;
SubVertex.add vs new_label (i,o) ;
new_vtx
let collapse_edge_pre g src label trg =
L.printf 1 "collapse_edge_pre: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_edge g src label trg)
;
remove_edge g src label trg
;
VertexMMap.iter (fun u l ->
remove_edge g u l trg ;
add_edge g (if Vertex.equal u trg then src else u) l src
) (snd trg).incoming
;
VertexMMap.iter (fun u l ->
remove_edge g trg l u ;
add_edge g src l (if Vertex.equal u trg then src else u)
) (snd trg).outgoing
;
remove_vertex g trg
let collapse_edge_post g src label trg =
L.printf 1 "collapse_edge_post: %a -> %a %a" Vertex.fmt src Vertex.fmt trg EdgeLabel.fmt label ;
assert(mem_edge g src label trg)
;
VertexMMap.iter (fun u l ->
remove_edge g u l src ;
add_edge g (if Vertex.equal u src then trg else u) l trg
) (snd src).incoming
;
remove_edge g src label trg ;
remove_vertex g src
let root_vertex g (k,a) =
IndexLabelSet.add g.roots (k,a.label)
let unroot_vertex g (k,a) =
IndexLabelSet.remove g.roots (k,a.label)
let fold_vertices_index fn g k z =
match Vertices.tryfind g.verts k with
| None ->
z
| Some(vs) ->
SubVertex.fold (fun label (incoming,outgoing) z ->
let v = (k, {label; incoming; outgoing}) in
if mem_vertex g v
then fn v z
else z
) vs z
let iter_vertices_index fn g k =
fold_vertices_index (fun v () -> fn v) g k ()
let fold_vertices fn g z =
Vertices.fold
(fun k vs z ->
SubVertex.fold
(fun l (i,o) a ->
let v = (k, {label=l; incoming=i; outgoing=o}) in
fn v a
) vs z
) g.verts z
let iter_vertices fn g =
fold_vertices (fun v () -> fn v) g ()
let fold_edges vertex_fn edge_fn g k z =
let edge_opt_fn prev_opt curr z =
match prev_opt with
| Some(prev,label) -> edge_fn (prev,label,curr) z
| None -> z
in
let memo = VertexISet.create ()
in
let rec walk prev_opt curr z =
if VertexISet.mem memo curr then
edge_opt_fn prev_opt curr z
else
let z = vertex_fn curr z in
let z = edge_opt_fn prev_opt curr z in
VertexISet.add memo curr ;
VertexMMap.fold (fun next label z ->
walk (Some(curr,label)) next z
) (snd curr).outgoing z
in
fold_vertices_index (walk None) g k z
let iter_edges vertex_fn edge_fn g k =
fold_edges (fun v () -> vertex_fn v) (fun e () -> edge_fn e) g k ()
let identify_vertices g =
let vertex_ids : int VertexIMap.t = VertexIMap.create () in
let count = ref 0 in
let identify_vertex v =
if not (VertexIMap.mem vertex_ids v) then (
VertexIMap.add vertex_ids v !count ;
incr count
)
in
iter_vertices identify_vertex g ;
vertex_ids
let cutpoints root =
let rec df_walk src ancestors visited cutpoints =
VertexMMap.fold (fun trg _ (visited, cutpoints) ->
if not (VertexSet.mem trg visited) then
df_walk trg (VertexSet.add trg ancestors) (VertexSet.add trg visited) cutpoints
else if not (VertexSet.mem trg ancestors) then
(visited, cutpoints)
else
(visited, VertexSet.add trg cutpoints)
) (snd src).outgoing (visited, cutpoints)
in
let roots = VertexSet.singleton root
in
snd (df_walk root roots roots VertexSet.empty)
Breadth - first search from CLR Algorithms textbook .
type visit_state = White | Grey | Black
let bfs g start =
State
let colour : visit_state VertexIMap.t = VertexIMap.create () in
let distance : int VertexIMap.t = VertexIMap.create () in
let predecessor : (vertex * e_label) option VertexIMap.t =
VertexIMap.create () in
let grey_q : vertex Queue.t = Queue.create () in
Initialize state .
iter_vertices
(fun v ->
VertexIMap.add colour v White ;
VertexIMap.add distance v max_int ;
VertexIMap.add predecessor v None
)
g ;
VertexIMap.add colour start Grey ;
VertexIMap.add distance start 0 ;
VertexIMap.add predecessor start None ;
Queue.push start grey_q;
while (not (Queue.is_empty grey_q)) do
L.incf 2 "( bfs visit" ; (fun _ -> L.decf 2 ") bfs visit") <&
let u = Queue.peek grey_q in
L.printf 2 " u --> v, where@\nu is %a" Vertex.fmt u ;
List.iter (fun (v,tr) ->
L.printf 2 " v is %a" Vertex.fmt v ;
if (VertexIMap.find colour v = White) then (
L.printf 2 " v is White" ;
VertexIMap.add colour v Grey ;
VertexIMap.add distance v ((VertexIMap.find distance u) + 1) ;
VertexIMap.add predecessor v (Some (u,tr)) ;
Queue.push v grey_q
) else
L.printf 2 " v is not White" ;
) (successors u) ;
let _ = Queue.pop grey_q in
VertexIMap.add colour u Black
done ;
(distance,predecessor)
let dfs_iter ?next:(next=fun () -> () ) ?forwards:(forwards=true) pre post starts =
let visited = VertexISet.create ()
in
let rec dfs_visit u =
L.incf 1 "( dfs visit: u is %a" Vertex.fmt u ; (fun _ -> L.decf 1 ") dfs visit") <&
if not (VertexISet.mem visited u) then (
VertexISet.add visited u ;
pre u ;
VertexMMap.iter (fun v _ ->
dfs_visit v
) (if forwards then (snd u).outgoing else (snd u).incoming) ;
post u
)
in
List.iter (fun start -> dfs_visit start ; next()) starts
Implementation from Introduction to Algorithms , Cormen et al
Section 23.5 Page 488
Section 23.5 Page 488
*)
let scc graph =
(fun scc_map -> assert(true$>
if Config.check_scc then (
let reaches x y =
let res = ref false in
dfs_iter (fun v -> if Vertex.equal v y then res := true) (fun _ -> ()) [x] ;
!res in
iter_vertices (fun x ->
iter_vertices (fun y ->
if not (Vertex.equal x y) then
let scc_x = VertexMap.find x scc_map in
let scc_y = VertexMap.find y scc_map in
if (scc_x == scc_y) <> (reaches x y && reaches y x) then
failwith "Graph.scc incorrect"
) graph
) graph
)
))<&
let vtxs = fold_vertices List.cons graph [] in
let rev_postorder = ref [] in
let skip = fun _ -> () in
let add_to rl = fun v -> rl := v :: !rl in
dfs_iter skip
(add_to rev_postorder)
vtxs ;
let current_scc = ref [] in
let scc_map = ref VertexMap.empty in
dfs_iter ~forwards:false
~next:(fun () ->
Add each vertex in the scc to the map , with the whole SCC
List.iter
(fun v ->
scc_map := VertexMap.add v !current_scc !scc_map
)
(!current_scc) ;
current_scc := []
)
skip
(add_to current_scc)
!rev_postorder ;
!scc_map
let dfs start =
let rev_preorder : (vertex list) ref = ref [] in
let rev_postorder : (vertex list) ref = ref [] in
let preorder_map : int VertexIMap.t = VertexIMap.create () in
let postorder_map : int VertexIMap.t = VertexIMap.create () in
let preorder_count = ref 0 in
let postorder_count = ref 0 in
dfs_iter
(fun u ->
rev_preorder := u :: !rev_preorder ;
VertexIMap.add preorder_map u !preorder_count ;
incr preorder_count
)
(fun u ->
rev_postorder := u :: !rev_postorder ;
VertexIMap.add postorder_map u !postorder_count ;
incr postorder_count
)
[start] ;
let preorder = List.rev (!rev_preorder) in
let postorder = List.rev (!rev_postorder) in
let preorder_num = VertexIMap.find preorder_map in
let postorder_num = VertexIMap.find postorder_map in
(preorder, postorder, preorder_num, postorder_num)
let dfs_revpost start =
let rev_postorder = ref [] in
let postorder_map = VertexIMap.create () in
let postorder_count = ref 0 in
dfs_iter (fun _ -> ()) (fun u ->
rev_postorder := u :: !rev_postorder ;
VertexIMap.add postorder_map u !postorder_count ;
incr postorder_count
) [start] ;
(!rev_postorder, VertexIMap.find postorder_map)
Dominance , based on " A Simple , Fast Dominance Algorithm " ( Cooper et al )
let immediate_dominators start =
let rev_postorder, postorder_num = dfs_revpost start in
let nnodes = (postorder_num (List.hd rev_postorder)) + 1 in
let undefined = -1 in
let doms = Array.create nnodes undefined in
doms.(postorder_num start) <- postorder_num start
;
let intersect i j =
let rec outer i j =
if i <> j then
let rec inner i j =
if i < j then
inner doms.(i) j
else
i
in
let i = inner i j in
let j = inner j i in
outer i j
else
i
in
outer i j
in
let not_root = List.tl rev_postorder
in
let rec build_dom_tree progress =
if progress then build_dom_tree (
List.fold (fun n progress ->
let preds = fold_preds (fun p _ preds -> postorder_num p :: preds) n [] in
let processed_pred, other_preds = List.take (fun p -> doms.(p) <> undefined) preds in
let new_idom =
List.fold (fun p new_idom ->
if doms.(p) <> undefined then
intersect p new_idom
else
new_idom
) other_preds processed_pred in
let b = postorder_num n in
if doms.(b) <> new_idom then (
doms.(b) <- new_idom ;
true
) else
progress
) not_root false
)
in
build_dom_tree true
;
(doms, rev_postorder, postorder_num)
let dominates doms postorder_num v u =
let i = postorder_num v
in
let rec loop j =
if j < i then
loop doms.(j)
else
j = i
in
loop (postorder_num u)
let dominance_frontier cfg start =
let doms, rev_postorder, postorder_num = immediate_dominators start in
let postorder = List.rev rev_postorder in
let postorder_vtx i =
List.nth postorder i
in
let dfset : VertexISet.t VertexIMap.t = VertexIMap.create () in
iter_vertices
(fun n ->
VertexIMap.add dfset n (VertexISet.create ())
)
cfg;
iter_vertices
(fun n ->
let preds = predecessors n in
if List.length preds >= 2 then (
let b = postorder_num n in
List.iter
(fun (p,_) ->
let runner = ref (postorder_num p) in
while (!runner <> doms.(b)) do
let runner_dfset = VertexIMap.find dfset (postorder_vtx !runner) in
VertexISet.add runner_dfset n;
runner := doms.(!runner)
done
)
preds
)
)
cfg;
let parent_of n =
try Some(postorder_vtx doms.(postorder_num n))
with Not_found -> None
in
let children_of =
let map : VertexISet.t VertexIMap.t = VertexIMap.create () in
iter_vertices (fun n -> VertexIMap.add map n (VertexISet.create ())) cfg ;
iter_vertices (fun n ->
Option.iter (fun p ->
Option.iter (fun p ->
VertexISet.add p n
) (VertexIMap.tryfind map p)
) (parent_of n)
) cfg ;
VertexISet.remove (VertexIMap.find map start) start;
VertexIMap.find map
in
(dfset, dominates doms postorder_num, parent_of, children_of)
let natural_loops cfg dominates =
n - > h(eader ) is a backedge if h dominates n
let backedges = fold_vertices
(fun n acc ->
let hs = List.filter
(fun (h,_) -> dominates h n)
(successors n)
in
acc @ (List.map (fun (h,_) -> (h,n)) hs)
)
cfg []
in
List.map
(fun (h,n) ->
let body = VertexISet.create () in
let s = Stack.create () in
VertexISet.add body h;
Stack.push n s;
while (not (Stack.is_empty s)) do
let d = Stack.pop s in
if (not (VertexISet.mem body d)) then (
VertexISet.add body d;
List.iter
(fun (p,_) -> Stack.push p s)
(predecessors d)
)
done;
(body,h,n)
)
backedges
Floyd - Warshall , and construct shortest - path .
From CLR Algorithms textbook .
From CLR Algorithms textbook. *)
type distance = Infinity | D of int
type pre = Nil | P of int
let is_infinity d = match d with Infinity -> true | _ -> false
let add d d' =
match d, d' with
| Infinity,_ | _,Infinity -> Infinity
| D(i), D(i') -> D(i+i')
let leq d d' =
match d, d' with
| Infinity, _ -> false
| _, Infinity -> true
| D(i), D(i') -> i <= i'
let fw g =
let vtx_to_i = identify_vertices g in
let n = (VertexIMap.fold (fun _vtx i size -> max i size) vtx_to_i 0) + 1 in
let i_to_vtx = IntHMap.create n in
VertexIMap.iter (fun vtx i ->
IntHMap.add i_to_vtx i vtx
) vtx_to_i
;
Is there an edge between the vertex indexed by i
and the one indexed by j ?
and the one indexed by j?*)
let edge i j =
List.exists (fun i' ->
Vertex.equal i' (IntHMap.find i_to_vtx j)
) (List.map fst (successors (IntHMap.find i_to_vtx i)))
in
let d = Array.make_matrix n n Infinity in
let pre = Array.make_matrix n n Nil in
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (i=j) then d.(i).(j) <- D(0)
else if (i <> j) then
if (edge i j) then d.(i).(j) <- D(1)
else d.(i).(j) <- Infinity
done
done
;
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (i=j || (is_infinity d.(i).(j))) then
pre.(i).(j) <- Nil
else
pre.(i).(j) <- P(i)
done
done
;
for k = 0 to (n-1) do
for i = 0 to (n-1) do
for j = 0 to (n-1) do
if (leq (d.(i).(j)) (add d.(i).(k) d.(k).(j))) then (
d.(i).(j) <- d.(i).(j) ;
pre.(i).(j) <- pre.(i).(j) ;
) else (
d.(i).(j) <- add d.(i).(k) d.(k).(j) ;
pre.(i).(j) <- pre.(k).(j) ;
)
done
done
done
;
Convert [ d ] and [ pre ] matrices into ( sparse ) Vtx->Vtx->data maps .
let d' = Array.make_matrix n n None in
let pre' = Array.make_matrix n n None in
for i = 0 to (n-1) do
for j = 0 to (n-1) do
d'.(i).(j) <- (match d.(i).(j) with
| D(d) -> Some d
| Infinity -> None );
pre'.(i).(j) <- (match pre.(i).(j) with
| P(p) -> Some p
| Nil -> None )
done
done
;
(vtx_to_i,i_to_vtx, d',pre')
let remove_unreachable g =
(fun () -> assert(true$>
let reachable = VertexISet.create () in
IndexLabelSet.iter (fun (k,label) ->
let incoming, outgoing = SubVertex.find (Vertices.find g.verts k) label in
let r = (k, {label; incoming; outgoing}) in
dfs_iter (fun v ->
VertexISet.add reachable v
) (fun _ -> ()) [r]
) g.roots ;
iter_vertices (fun v ->
assert( VertexISet.mem reachable v
|| L.warnf "remove_unreachable failed to remove: %a" Vertex.fmt v )
) g
)) <&
iter_vertices (remove_vertex g) g
let copy g0 src =
let g = create ()
in
let m =
fold_edges
(fun v m ->
VertexMap.add v (add_vertex g (index_of v, label_of v)) m
)
(fun (u,l,v) m ->
match VertexMap.tryfind u m, VertexMap.tryfind v m with
| Some(u'), Some(v') ->
add_edge g u' l v'; m
| _ ->
m
)
g0
(index_of src)
VertexMap.empty
in
(m, g)
let slice src trg g0 =
let vtx_to_id,_, distance,_ = fw g0
in
let trg_id = VertexIMap.find vtx_to_id trg
in
let g = create ()
in
let m =
fold_edges
(fun v m ->
assert( distance.(VertexIMap.find vtx_to_id src).(VertexIMap.find vtx_to_id v) <> None );
if distance.(VertexIMap.find vtx_to_id v).(trg_id) <> None then
VertexMap.add v (add_vertex g (index_of v, label_of v)) m
else
m
)
(fun (u,l,v) m ->
match VertexMap.tryfind u m, VertexMap.tryfind v m with
| Some(u'), Some(v') ->
add_edge g u' l v'; m
| _ ->
m
)
g0
(index_of src)
VertexMap.empty
in
(m, g)
let calculate_margin len =
let rec loop height width =
if width /. height > Config.margin_frac then
loop (height +. 1.) (width /. 2.)
else
int_of_float width
in
if len <= 40 then 40 else
loop 1. (float_of_int len)
let reprint msg =
let src_buf = Buffer.create 128 in
let ff = Format.formatter_of_buffer src_buf in
Format.pp_set_margin ff max_int ;
msg ff ;
Format.pp_print_flush ff () ;
let len = Buffer.length src_buf in
let src_buf = Buffer.create len in
let ff = Format.formatter_of_buffer src_buf in
Format.pp_set_margin ff (calculate_margin len) ;
msg ff ;
Format.pp_print_flush ff () ;
let dst_buf = Buffer.create len in
for ind = 0 to Buffer.length src_buf - 1 do
match Buffer.nth src_buf ind with
| '\n' -> Buffer.add_string dst_buf "\\l"
| '\\' -> Buffer.add_string dst_buf "\\\\"
| '\"' -> Buffer.add_string dst_buf "\\\""
| char -> Buffer.add_char dst_buf char
done ;
Buffer.contents dst_buf
let writers g out =
let id =
let m = identify_vertices g in
VertexIMap.find m
in
let write_vertex v =
let msg v = reprint (fun ff -> Vertex.fmt ff v) in
Printf.bprintf out "%i [shape=box,label=\"v %i: %s\\l\"]\n" (id v) (id v) (msg v)
in
let write_edge (src,lab,trg) =
let msg lab = reprint (fun ff -> EdgeLabel.fmt ff lab) in
Printf.bprintf out "%i -> %i [label=\"%s\\l\"]\n" (id src) (id trg) (msg lab)
in
(write_vertex, write_edge, id)
let write_dot_header out =
Printf.bprintf out "digraph g {\n" ;
if Config.font <> "" then (
Printf.bprintf out "graph [fontname=\"%s\"]\n" Config.font ;
Printf.bprintf out "node [fontname=\"%s\"]\n" Config.font ;
Printf.bprintf out "edge [fontname=\"%s\"]\n" Config.font ;
)
let write_dot_footer out =
Printf.bprintf out "}\n"
let cfg_write_dot cfg children_of k out =
let write_vertex, write_edge, id = writers cfg out in
write_dot_header out ;
iter_edges write_vertex write_edge cfg k ;
iter_vertices (fun n ->
VertexISet.iter (fun m ->
Printf.bprintf out "%i -> %i [dir=none, weight=3, penwidth=3, color=\"#660000\"]\n" (id n) (id m))
(children_of n);
) cfg;
write_dot_footer out
let write_dot g k out =
let write_vertex, write_edge, _ = writers g out
in
write_dot_header out ;
iter_edges write_vertex write_edge g k ;
write_dot_footer out
let write_dot_partitioned fn g roots out =
let write_vertex, write_edge, _ = writers g out
in
let vs = ref [] in
List.iter (iter_edges (fun v -> vs := v :: !vs) (fun _ -> ()) g) roots ;
let partitions =
List.classify (fun x y ->
Option.equal (fun a b -> fst a = fst b)
(fn (index_of x)) (fn (index_of y))
) !vs in
write_dot_header out ;
List.iter (fun vs ->
match fn (index_of (List.hd vs)) with
| None -> ()
| Some(name,msg) ->
Printf.bprintf out "subgraph cluster%s {\nlabel=\"%s\"\n" name (reprint msg) ;
List.iter write_vertex vs ;
Printf.bprintf out "}\n"
) partitions ;
List.iter (fun root ->
iter_edges
(fun v ->
match fn (index_of v) with
| Some _ -> ()
| None -> write_vertex v
)
write_edge
g root
) roots ;
write_dot_footer out
end
|
e648d140faaab3a966c0674a4771c287459d7252a0ba7c4d7531d6448eaf4f99 | periodic/HilbertRTree | Internal.hs | module Data.HRTree.Internal where
import Data.HRTree.Geometry
import Data.HRTree.Hilbert
import Data.Word
import qualified Data.List as L (insert, unfoldr)
-- | Capacity constants. TODO: Make these tunable.
nodeCapacity = 4
leafCapacity = 4
splitOrder = 1
-- | Type alias for the type we're going to use as a key.
type Key = Word32
-- | Individual records of an internal node.
data (SpatiallyBounded a) => NodeRecord a =
NR { nrMbr :: BoundingBox
, nrKey :: Key
, nrChild :: RTree a
}
-- Instances for the node-records.
instance (SpatiallyBounded a) => Eq (NodeRecord a) where
n1 == n2 = nrKey n1 == nrKey n2
instance (SpatiallyBounded a) => Ord (NodeRecord a) where
n1 <= n2 = nrKey n1 <= nrKey n2
instance (SpatiallyBounded a, Show a) => Show (NodeRecord a) where
show (NR _ _ child) = show child
-- | Individual records of a leaf node.
data (SpatiallyBounded a) => LeafRecord a =
LR { lrMbr :: BoundingBox
, lrKey :: Key
, lrObj :: a
}
-- Instances for leaf-records
instance (SpatiallyBounded a) => Eq (LeafRecord a) where
l1 == l2 = lrKey l1 == lrKey l2
instance (SpatiallyBounded a) => Ord (LeafRecord a) where
l1 <= l2 = lrKey l1 <= lrKey l2
instance (SpatiallyBounded a, Show a) => Show (LeafRecord a) where
show (LR _ _ obj) = show obj
{- | The RTree type, which is really just a node, either an internal node or a leaf.
-}
data (SpatiallyBounded a) => RTree a = Node [NodeRecord a]
| Leaf [LeafRecord a]
-- | INstances for RTree
instance (SpatiallyBounded a) => SpatiallyBounded (RTree a) where
boundingBox (Node records) = boundingBox . map nrMbr $ records
boundingBox (Leaf records) = boundingBox . map lrMbr $ records
instance (SpatiallyBounded a, Show a) => Show (RTree a) where
show (Node records) = "<" ++ show records ++ ">"
show (Leaf records) = "<" ++ show records ++ ">"
{- | Create an empty RTree. An empty tree is just a single leaf.
-}
empty :: (SpatiallyBounded a) => RTree a
empty = Leaf []
{-| Insert a record into the tree.
-}
insert :: (SpatiallyBounded a) => a -> RTree a -> RTree a
insert item tree =
let record = makeLeafRecord item
in case insertK record tree of
[] -> error "Empty tree returned."
[r] -> r
rs -> Node . map makeNodeRecord $ rs
{-| Search the tree, returning all records that have intersecting bounding boxes with the search item.
-}
search :: (SpatiallyBounded a, SpatiallyBounded b) => a -> RTree b -> [b]
search target = let mbr = boundingBox target
in search_mbr mbr
where
checkNodeRecord mbr r = if bbIntersect mbr (nrMbr r)
then search_mbr mbr . nrChild $ r
else []
checkLeafRecord mbr r = if bbIntersect mbr (lrMbr r)
then (:[]) . lrObj $ r
else []
search_mbr mbr (Node records) = concatMap (checkNodeRecord mbr) records
search_mbr mbr (Leaf records) = concatMap (checkLeafRecord mbr) records
{------------------------------------------------------------
- Non-exported functions
------------------------------------------------------------}
-- | Get the number of records in a node
numRecords :: (SpatiallyBounded a) => RTree a -> Int
numRecords (Node rs) = length rs
numRecords (Leaf rs) = length rs
| Wrap a node in a record , getting the right key and mbr .
makeNodeRecord :: (SpatiallyBounded a) => RTree a -> NodeRecord a
makeNodeRecord t = NR (boundingBox t) (getNodeKey t) t
| Wrap an item in a record , calculating the key and mbr .
makeLeafRecord :: (SpatiallyBounded a) => a -> LeafRecord a
makeLeafRecord i = LR (boundingBox i) (getKey i) i
| Make a set of leaf records from a set of LeafRecords , respecting the capacity .
makeLeaves :: (SpatiallyBounded a) => [LeafRecord a] -> [RTree a]
makeLeaves records = let nodeCount = ((length records - 1) `div` leafCapacity + 1)
in map Leaf . distribute nodeCount $ records
| Make a set of node records from a set of NodeRecords , respecting the capacity .
makeNodes :: (SpatiallyBounded a) => [NodeRecord a] -> [RTree a]
makeNodes records = let nodeCount = ((length records - 1) `div` nodeCapacity + 1)
in map Node . distribute nodeCount $ records
-- | Split a list into n sublists evenly.
distribute :: Int -> [a] -> [[a]]
distribute n xs = L.unfoldr split xs
where
limit = ceiling (fromIntegral (length xs) / fromIntegral n)
split [] = Nothing
split ys = Just . splitAt limit $ ys
| Redistribute records among a set of nodes . Note that nodes must be of the same type . If not , we 're in trouble .
redistribute :: (SpatiallyBounded a) => [RTree a] -> [RTree a]
redistribute [] = []
redistribute [a] = [a]
redistribute [(Node as),(Node bs)] = makeNodes (as ++ bs)
redistribute [(Node as),(Node bs),(Node cs)] = makeNodes (as ++ bs ++ cs)
redistribute [(Leaf as),(Leaf bs)] = makeLeaves (as ++ bs)
redistribute [(Leaf as),(Leaf bs),(Leaf cs)] = makeLeaves (as ++ bs ++ cs)
redistribute nodes = if length nodes > 3
then error "Redistributing among too many nodes."
else error "Incompatible node types. Inconsistent tree."
-- | Get the key for this object.
getKey :: (SpatiallyBounded a) => a -> Key
getKey item = case center item of
Just p -> hilbertValue 16 p
Nothing -> 0
-- | Get the key for a node.
getNodeKey :: (SpatiallyBounded a) => RTree a -> Key
getNodeKey (Node records) = foldr (max . nrKey) 0 records
getNodeKey (Leaf records) = foldr (max . lrKey) 0 records
| Inserting a leaf record in the tree .
-
- For a leaf this just means taking the set of all leaf records and allocate
- them to one or more nodes .
-
- For a node this requires we find the right sub - node to insert in , which is
- the first node for which the key is greater than or equal to the key for the
- object we are inserting .
-
- This function is the hairiest part of the program . It really needs some
- cleanup . I 'm filing that under future enhancements .
-
- For a leaf this just means taking the set of all leaf records and allocate
- them to one or more nodes.
-
- For a node this requires we find the right sub-node to insert in, which is
- the first node for which the key is greater than or equal to the key for the
- object we are inserting.
-
- This function is the hairiest part of the program. It really needs some
- cleanup. I'm filing that under future enhancements.
-}
insertK :: (SpatiallyBounded a) => LeafRecord a -> RTree a -> [RTree a]
insertK r (Leaf records) = makeLeaves . L.insert r $ records
insertK leaf@(LR _ key _) (Node records) = makeNodes . findNode [] $ records
where
findNode [] [] = return . makeNodeRecord . Leaf . return $ leaf
findNode (p:[]) [] = map makeNodeRecord . insertK leaf . nrChild $ p
findNode (p:p2:prev)[] = (reverse prev ++) . map makeNodeRecord . redistribute . (nrChild p2 :) . insertK leaf . nrChild $ p
findNode prev (r:next)=
if nrKey r >= key
then insertHere prev r next
else findNode (r:prev) next
insertHere ps r ns = let newNodes = insertK leaf (nrChild r)
newRecords = map makeNodeRecord newNodes
in if length newNodes == 1
then reverse ps ++ newRecords ++ ns
else case (ps,ns) of
([], [] ) -> newRecords
((p:ps), [] ) -> reverse ps ++ map makeNodeRecord (redistribute (nrChild p : newNodes))
([], (n:ns)) -> map makeNodeRecord (redistribute (newNodes ++ [nrChild n])) ++ ns
((p:ps), (n:ns)) -> let pSize = numRecords . nrChild $ p
nSize = numRecords . nrChild $ n
in if (pSize < nSize)
then reverse ps ++ map makeNodeRecord (redistribute (nrChild p : newNodes)) ++ n:ns
else reverse (p:ps) ++ map makeNodeRecord (redistribute (newNodes ++ [nrChild n])) ++ ns
| null | https://raw.githubusercontent.com/periodic/HilbertRTree/a90ef17578a201153bd13a41582184808cc1947a/Data/HRTree/Internal.hs | haskell | | Capacity constants. TODO: Make these tunable.
| Type alias for the type we're going to use as a key.
| Individual records of an internal node.
Instances for the node-records.
| Individual records of a leaf node.
Instances for leaf-records
| The RTree type, which is really just a node, either an internal node or a leaf.
| INstances for RTree
| Create an empty RTree. An empty tree is just a single leaf.
| Insert a record into the tree.
| Search the tree, returning all records that have intersecting bounding boxes with the search item.
-----------------------------------------------------------
- Non-exported functions
-----------------------------------------------------------
| Get the number of records in a node
| Split a list into n sublists evenly.
| Get the key for this object.
| Get the key for a node. | module Data.HRTree.Internal where
import Data.HRTree.Geometry
import Data.HRTree.Hilbert
import Data.Word
import qualified Data.List as L (insert, unfoldr)
nodeCapacity = 4
leafCapacity = 4
splitOrder = 1
type Key = Word32
data (SpatiallyBounded a) => NodeRecord a =
NR { nrMbr :: BoundingBox
, nrKey :: Key
, nrChild :: RTree a
}
instance (SpatiallyBounded a) => Eq (NodeRecord a) where
n1 == n2 = nrKey n1 == nrKey n2
instance (SpatiallyBounded a) => Ord (NodeRecord a) where
n1 <= n2 = nrKey n1 <= nrKey n2
instance (SpatiallyBounded a, Show a) => Show (NodeRecord a) where
show (NR _ _ child) = show child
data (SpatiallyBounded a) => LeafRecord a =
LR { lrMbr :: BoundingBox
, lrKey :: Key
, lrObj :: a
}
instance (SpatiallyBounded a) => Eq (LeafRecord a) where
l1 == l2 = lrKey l1 == lrKey l2
instance (SpatiallyBounded a) => Ord (LeafRecord a) where
l1 <= l2 = lrKey l1 <= lrKey l2
instance (SpatiallyBounded a, Show a) => Show (LeafRecord a) where
show (LR _ _ obj) = show obj
data (SpatiallyBounded a) => RTree a = Node [NodeRecord a]
| Leaf [LeafRecord a]
instance (SpatiallyBounded a) => SpatiallyBounded (RTree a) where
boundingBox (Node records) = boundingBox . map nrMbr $ records
boundingBox (Leaf records) = boundingBox . map lrMbr $ records
instance (SpatiallyBounded a, Show a) => Show (RTree a) where
show (Node records) = "<" ++ show records ++ ">"
show (Leaf records) = "<" ++ show records ++ ">"
empty :: (SpatiallyBounded a) => RTree a
empty = Leaf []
insert :: (SpatiallyBounded a) => a -> RTree a -> RTree a
insert item tree =
let record = makeLeafRecord item
in case insertK record tree of
[] -> error "Empty tree returned."
[r] -> r
rs -> Node . map makeNodeRecord $ rs
search :: (SpatiallyBounded a, SpatiallyBounded b) => a -> RTree b -> [b]
search target = let mbr = boundingBox target
in search_mbr mbr
where
checkNodeRecord mbr r = if bbIntersect mbr (nrMbr r)
then search_mbr mbr . nrChild $ r
else []
checkLeafRecord mbr r = if bbIntersect mbr (lrMbr r)
then (:[]) . lrObj $ r
else []
search_mbr mbr (Node records) = concatMap (checkNodeRecord mbr) records
search_mbr mbr (Leaf records) = concatMap (checkLeafRecord mbr) records
numRecords :: (SpatiallyBounded a) => RTree a -> Int
numRecords (Node rs) = length rs
numRecords (Leaf rs) = length rs
| Wrap a node in a record , getting the right key and mbr .
makeNodeRecord :: (SpatiallyBounded a) => RTree a -> NodeRecord a
makeNodeRecord t = NR (boundingBox t) (getNodeKey t) t
| Wrap an item in a record , calculating the key and mbr .
makeLeafRecord :: (SpatiallyBounded a) => a -> LeafRecord a
makeLeafRecord i = LR (boundingBox i) (getKey i) i
| Make a set of leaf records from a set of LeafRecords , respecting the capacity .
makeLeaves :: (SpatiallyBounded a) => [LeafRecord a] -> [RTree a]
makeLeaves records = let nodeCount = ((length records - 1) `div` leafCapacity + 1)
in map Leaf . distribute nodeCount $ records
| Make a set of node records from a set of NodeRecords , respecting the capacity .
makeNodes :: (SpatiallyBounded a) => [NodeRecord a] -> [RTree a]
makeNodes records = let nodeCount = ((length records - 1) `div` nodeCapacity + 1)
in map Node . distribute nodeCount $ records
distribute :: Int -> [a] -> [[a]]
distribute n xs = L.unfoldr split xs
where
limit = ceiling (fromIntegral (length xs) / fromIntegral n)
split [] = Nothing
split ys = Just . splitAt limit $ ys
| Redistribute records among a set of nodes . Note that nodes must be of the same type . If not , we 're in trouble .
redistribute :: (SpatiallyBounded a) => [RTree a] -> [RTree a]
redistribute [] = []
redistribute [a] = [a]
redistribute [(Node as),(Node bs)] = makeNodes (as ++ bs)
redistribute [(Node as),(Node bs),(Node cs)] = makeNodes (as ++ bs ++ cs)
redistribute [(Leaf as),(Leaf bs)] = makeLeaves (as ++ bs)
redistribute [(Leaf as),(Leaf bs),(Leaf cs)] = makeLeaves (as ++ bs ++ cs)
redistribute nodes = if length nodes > 3
then error "Redistributing among too many nodes."
else error "Incompatible node types. Inconsistent tree."
getKey :: (SpatiallyBounded a) => a -> Key
getKey item = case center item of
Just p -> hilbertValue 16 p
Nothing -> 0
getNodeKey :: (SpatiallyBounded a) => RTree a -> Key
getNodeKey (Node records) = foldr (max . nrKey) 0 records
getNodeKey (Leaf records) = foldr (max . lrKey) 0 records
| Inserting a leaf record in the tree .
-
- For a leaf this just means taking the set of all leaf records and allocate
- them to one or more nodes .
-
- For a node this requires we find the right sub - node to insert in , which is
- the first node for which the key is greater than or equal to the key for the
- object we are inserting .
-
- This function is the hairiest part of the program . It really needs some
- cleanup . I 'm filing that under future enhancements .
-
- For a leaf this just means taking the set of all leaf records and allocate
- them to one or more nodes.
-
- For a node this requires we find the right sub-node to insert in, which is
- the first node for which the key is greater than or equal to the key for the
- object we are inserting.
-
- This function is the hairiest part of the program. It really needs some
- cleanup. I'm filing that under future enhancements.
-}
insertK :: (SpatiallyBounded a) => LeafRecord a -> RTree a -> [RTree a]
insertK r (Leaf records) = makeLeaves . L.insert r $ records
insertK leaf@(LR _ key _) (Node records) = makeNodes . findNode [] $ records
where
findNode [] [] = return . makeNodeRecord . Leaf . return $ leaf
findNode (p:[]) [] = map makeNodeRecord . insertK leaf . nrChild $ p
findNode (p:p2:prev)[] = (reverse prev ++) . map makeNodeRecord . redistribute . (nrChild p2 :) . insertK leaf . nrChild $ p
findNode prev (r:next)=
if nrKey r >= key
then insertHere prev r next
else findNode (r:prev) next
insertHere ps r ns = let newNodes = insertK leaf (nrChild r)
newRecords = map makeNodeRecord newNodes
in if length newNodes == 1
then reverse ps ++ newRecords ++ ns
else case (ps,ns) of
([], [] ) -> newRecords
((p:ps), [] ) -> reverse ps ++ map makeNodeRecord (redistribute (nrChild p : newNodes))
([], (n:ns)) -> map makeNodeRecord (redistribute (newNodes ++ [nrChild n])) ++ ns
((p:ps), (n:ns)) -> let pSize = numRecords . nrChild $ p
nSize = numRecords . nrChild $ n
in if (pSize < nSize)
then reverse ps ++ map makeNodeRecord (redistribute (nrChild p : newNodes)) ++ n:ns
else reverse (p:ps) ++ map makeNodeRecord (redistribute (newNodes ++ [nrChild n])) ++ ns
|
d12e26bac645423dbbcd23732c48c4b09d247ef5d87d5dfa5b31ba8a25e274f5 | kelamg/HtDP2e-workthrough | ex349.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex349) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct add (left right))
(define-struct mul (left right))
; An Atom is one of:
; – Number
; – String
; – Symbol
An S - expr is one of :
– Atom
– SL
An SL is one of :
; – '()
– ( cons S - expr SL )
(define WRONG "parse: invalid S-expr")
;; Any -> Boolean
;; produces true if x is of atomic
(check-expect (atom? 2) #true)
(check-expect (atom? "a") #true)
(check-expect (atom? 'x) #true)
(check-expect (atom? (make-posn 40 50)) #false)
(define (atom? x)
(or (number? x) (string? x) (symbol? x)))
;; S-expr -> BSL-expr
produces a BSL - expr from s
iff s is the result of quoting a BSL expression
that has a BSL - expr representative
(check-expect
(parse 42) 42)
(check-expect
(parse '(* 6 7)) (make-mul 6 7))
(check-expect
(parse '(+ 2 (* 4 10))) (make-add 2 (make-mul 4 10)))
(check-error (parse "ooops"))
(check-error (parse 'ooops))
(check-error (parse '(+ 1)))
(check-error (parse '(/ (* 42 10) 10)))
(check-error (parse '(* 3 2 7)))
; S-expr -> BSL-expr
(define (parse s)
(cond
[(atom? s) (parse-atom s)]
[else (parse-sl s)]))
SL - > BSL - expr
(define (parse-sl s)
(local ((define L (length s)))
(cond
[(< L 3) (error WRONG)]
[(and (= L 3) (symbol? (first s)))
(cond
[(symbol=? (first s) '+)
(make-add (parse (second s)) (parse (third s)))]
[(symbol=? (first s) '*)
(make-mul (parse (second s)) (parse (third s)))]
[else (error WRONG)])]
[else (error WRONG)])))
; Atom -> BSL-expr
(define (parse-atom s)
(cond
[(number? s) s]
[(string? s) (error WRONG)]
[(symbol? s) (error WRONG)]))
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Intertwined-Data/ex349.rkt | racket | about the language level of this file in a form that our tools can easily process.
An Atom is one of:
– Number
– String
– Symbol
– '()
Any -> Boolean
produces true if x is of atomic
S-expr -> BSL-expr
S-expr -> BSL-expr
Atom -> BSL-expr | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex349) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct add (left right))
(define-struct mul (left right))
An S - expr is one of :
– Atom
– SL
An SL is one of :
– ( cons S - expr SL )
(define WRONG "parse: invalid S-expr")
(check-expect (atom? 2) #true)
(check-expect (atom? "a") #true)
(check-expect (atom? 'x) #true)
(check-expect (atom? (make-posn 40 50)) #false)
(define (atom? x)
(or (number? x) (string? x) (symbol? x)))
produces a BSL - expr from s
iff s is the result of quoting a BSL expression
that has a BSL - expr representative
(check-expect
(parse 42) 42)
(check-expect
(parse '(* 6 7)) (make-mul 6 7))
(check-expect
(parse '(+ 2 (* 4 10))) (make-add 2 (make-mul 4 10)))
(check-error (parse "ooops"))
(check-error (parse 'ooops))
(check-error (parse '(+ 1)))
(check-error (parse '(/ (* 42 10) 10)))
(check-error (parse '(* 3 2 7)))
(define (parse s)
(cond
[(atom? s) (parse-atom s)]
[else (parse-sl s)]))
SL - > BSL - expr
(define (parse-sl s)
(local ((define L (length s)))
(cond
[(< L 3) (error WRONG)]
[(and (= L 3) (symbol? (first s)))
(cond
[(symbol=? (first s) '+)
(make-add (parse (second s)) (parse (third s)))]
[(symbol=? (first s) '*)
(make-mul (parse (second s)) (parse (third s)))]
[else (error WRONG)])]
[else (error WRONG)])))
(define (parse-atom s)
(cond
[(number? s) s]
[(string? s) (error WRONG)]
[(symbol? s) (error WRONG)]))
|
006b8e52595df4d333a60c289ada34f8e0b546809154bc0ebd00a4748846a250 | herd/herdtools7 | channel_test.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Tests for the Channel module. *)
let pp_int_list = Test.pp_int_list
let pp_string_list = Test.pp_string_list
let tests = [
"Channel.read_lines and Channel.write_lines", (fun () ->
let in_fd, out_fd = Unix.pipe () in
let in_ch, out_ch = Unix.in_channel_of_descr in_fd, Unix.out_channel_of_descr out_fd in
let lines = ["mew"; "purr"] in
Channel.write_lines out_ch lines ;
close_out out_ch ;
let actual = Channel.read_lines in_ch in
close_in in_ch ;
if Test.string_list_compare lines actual <> 0 then
Test.fail (Printf.sprintf "Expected %s, got %s" (pp_string_list lines) (pp_string_list actual))
);
"Channel.map_lines applies f", (fun () ->
let in_fd, out_fd = Unix.pipe () in
let in_ch, out_ch = Unix.in_channel_of_descr in_fd, Unix.out_channel_of_descr out_fd in
let lines = ["mew"; "purr"] in
Channel.write_lines out_ch lines ;
close_out out_ch ;
let expected = [3; 4] in
let actual = Channel.map_lines String.length in_ch in
close_in in_ch ;
if Test.int_list_compare expected actual <> 0 then
Test.fail (Printf.sprintf "Expected %s, got %s" (pp_int_list expected) (pp_int_list actual))
);
]
let () = Test.run tests
| null | https://raw.githubusercontent.com/herd/herdtools7/b86aec8db64f8812e19468893deb1cdf5bbcfb83/internal/lib/tests/channel_test.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Tests for the Channel module. | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
let pp_int_list = Test.pp_int_list
let pp_string_list = Test.pp_string_list
let tests = [
"Channel.read_lines and Channel.write_lines", (fun () ->
let in_fd, out_fd = Unix.pipe () in
let in_ch, out_ch = Unix.in_channel_of_descr in_fd, Unix.out_channel_of_descr out_fd in
let lines = ["mew"; "purr"] in
Channel.write_lines out_ch lines ;
close_out out_ch ;
let actual = Channel.read_lines in_ch in
close_in in_ch ;
if Test.string_list_compare lines actual <> 0 then
Test.fail (Printf.sprintf "Expected %s, got %s" (pp_string_list lines) (pp_string_list actual))
);
"Channel.map_lines applies f", (fun () ->
let in_fd, out_fd = Unix.pipe () in
let in_ch, out_ch = Unix.in_channel_of_descr in_fd, Unix.out_channel_of_descr out_fd in
let lines = ["mew"; "purr"] in
Channel.write_lines out_ch lines ;
close_out out_ch ;
let expected = [3; 4] in
let actual = Channel.map_lines String.length in_ch in
close_in in_ch ;
if Test.int_list_compare expected actual <> 0 then
Test.fail (Printf.sprintf "Expected %s, got %s" (pp_int_list expected) (pp_int_list actual))
);
]
let () = Test.run tests
|
15d305b3901c98bb9072e214a0c7e6ac229dfa6f13eb72cb8c2e1d68c6d8a51e | basho/sidejob | sidejob_resource_stats.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you 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
%%
%% -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(sidejob_resource_stats).
-behaviour(gen_server).
%% API
-export([reg_name/1, start_link/2, report/5, init_stats/1, stats/1, usage/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {worker_reports = dict:new(),
stats_ets = undefined,
usage = 0,
rejected = 0,
in = 0,
out = 0,
stats_60s = sidejob_stat:new(),
next_stats_60s = sidejob_stat:new(),
left_60s = 60,
stats_total = sidejob_stat:new()}).
%%%===================================================================
%%% API
%%%===================================================================
reg_name(Name) when is_atom(Name) ->
reg_name(atom_to_binary(Name, latin1));
reg_name(Name) ->
binary_to_atom(<<Name/binary, "_stats">>, latin1).
start_link(RegName, StatsETS) ->
gen_server:start_link({local, RegName}, ?MODULE, [StatsETS], []).
%% @doc
%% Used by {@link sidejob_worker} processes to report per-worker statistics
report(Name, Id, Usage, In, Out) ->
gen_server:cast(Name, {report, Id, Usage, In, Out}).
%% @doc
%% Used by {@link sidejob_resource_sup} to initialize a newly created
%% stats ETS table to ensure the table is non-empty before bringing a
%% resource online
init_stats(StatsETS) ->
EmptyStats = compute(#state{}),
ets:insert(StatsETS, [{rejected, 0},
{usage, 0},
{stats, EmptyStats}]).
%% @doc
Return the computed stats for the given sidejob resource
stats(Name) ->
StatsETS = Name:stats_ets(),
ets:lookup_element(StatsETS, stats, 2).
%% @doc
Return the current usage for the given sidejob resource
usage(Name) ->
StatsETS = Name:stats_ets(),
ets:lookup_element(StatsETS, usage, 2).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([StatsETS]) ->
schedule_tick(),
{ok, #state{stats_ets=StatsETS}}.
handle_call(get_stats, _From, State) ->
{reply, compute(State), State};
handle_call(usage, _From, State=#state{usage=Usage}) ->
{reply, Usage, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
handle_cast({report, Id, UsageVal, InVal, OutVal},
State=#state{worker_reports=Reports}) ->
Reports2 = dict:store(Id, {UsageVal, InVal, OutVal}, Reports),
State2 = State#state{worker_reports=Reports2},
{noreply, State2};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(tick, State) ->
schedule_tick(),
State2 = tick(State),
{noreply, State2};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
schedule_tick() ->
erlang:send_after(1000, self(), tick).
%% Aggregate all reported worker stats into unified stat report for
%% this resource
tick(State=#state{stats_ets=StatsETS,
left_60s=Left60,
next_stats_60s=Next60,
stats_total=Total}) ->
{Usage, In, Out} = combine_reports(State),
Rejected = ets:update_counter(StatsETS, rejected, 0),
ets:update_counter(StatsETS, rejected, {2,-Rejected,0,0}),
NewNext60 = sidejob_stat:add(Rejected, In, Out, Next60),
NewTotal = sidejob_stat:add(Rejected, In, Out, Total),
State2 = State#state{usage=Usage,
rejected=Rejected,
in=In,
out=Out,
next_stats_60s=NewNext60,
stats_total=NewTotal},
State3 = case Left60 of
0 ->
State2#state{left_60s=59,
stats_60s=NewNext60,
next_stats_60s=sidejob_stat:new()};
_ ->
State2#state{left_60s=Left60-1}
end,
ets:insert(StatsETS, [{usage, Usage},
{stats, compute(State3)}]),
State3.
%% Total all reported worker stats into a single sum for each metric
combine_reports(#state{worker_reports=Reports}) ->
dict:fold(fun(_, {Usage, In, Out}, {UsageAcc, InAcc, OutAcc}) ->
{UsageAcc + Usage, InAcc + In, OutAcc + Out}
end, {0,0,0}, Reports).
compute(#state{usage=Usage, rejected=Rejected, in=In, out=Out,
stats_60s=Stats60s, stats_total=StatsTotal}) ->
{Usage60, Rejected60, InAvg60, InMax60, OutAvg60, OutMax60} =
sidejob_stat:compute(Stats60s),
{UsageTot, RejectedTot, InAvgTot, InMaxTot, OutAvgTot, OutMaxTot} =
sidejob_stat:compute(StatsTotal),
[{usage, Usage},
{rejected, Rejected},
{in_rate, In},
{out_rate, Out},
{usage_60s, Usage60},
{rejected_60s, Rejected60},
{avg_in_rate_60s, InAvg60},
{max_in_rate_60s, InMax60},
{avg_out_rate_60s, OutAvg60},
{max_out_rate_60s, OutMax60},
{usage_total, UsageTot},
{rejected_total, RejectedTot},
{avg_in_rate_total, InAvgTot},
{max_in_rate_total, InMaxTot},
{avg_out_rate_total, OutAvgTot},
{max_out_rate_total, OutMaxTot}].
| null | https://raw.githubusercontent.com/basho/sidejob/1c377578c0956e91ebbb98a798c5d4b6d0959c99/src/sidejob_resource_stats.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
API
gen_server callbacks
===================================================================
API
===================================================================
@doc
Used by {@link sidejob_worker} processes to report per-worker statistics
@doc
Used by {@link sidejob_resource_sup} to initialize a newly created
stats ETS table to ensure the table is non-empty before bringing a
resource online
@doc
@doc
===================================================================
gen_server callbacks
===================================================================
===================================================================
===================================================================
Aggregate all reported worker stats into unified stat report for
this resource
Total all reported worker stats into a single sum for each metric | Copyright ( c ) 2013 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(sidejob_resource_stats).
-behaviour(gen_server).
-export([reg_name/1, start_link/2, report/5, init_stats/1, stats/1, usage/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {worker_reports = dict:new(),
stats_ets = undefined,
usage = 0,
rejected = 0,
in = 0,
out = 0,
stats_60s = sidejob_stat:new(),
next_stats_60s = sidejob_stat:new(),
left_60s = 60,
stats_total = sidejob_stat:new()}).
reg_name(Name) when is_atom(Name) ->
reg_name(atom_to_binary(Name, latin1));
reg_name(Name) ->
binary_to_atom(<<Name/binary, "_stats">>, latin1).
start_link(RegName, StatsETS) ->
gen_server:start_link({local, RegName}, ?MODULE, [StatsETS], []).
report(Name, Id, Usage, In, Out) ->
gen_server:cast(Name, {report, Id, Usage, In, Out}).
init_stats(StatsETS) ->
EmptyStats = compute(#state{}),
ets:insert(StatsETS, [{rejected, 0},
{usage, 0},
{stats, EmptyStats}]).
Return the computed stats for the given sidejob resource
stats(Name) ->
StatsETS = Name:stats_ets(),
ets:lookup_element(StatsETS, stats, 2).
Return the current usage for the given sidejob resource
usage(Name) ->
StatsETS = Name:stats_ets(),
ets:lookup_element(StatsETS, usage, 2).
init([StatsETS]) ->
schedule_tick(),
{ok, #state{stats_ets=StatsETS}}.
handle_call(get_stats, _From, State) ->
{reply, compute(State), State};
handle_call(usage, _From, State=#state{usage=Usage}) ->
{reply, Usage, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
handle_cast({report, Id, UsageVal, InVal, OutVal},
State=#state{worker_reports=Reports}) ->
Reports2 = dict:store(Id, {UsageVal, InVal, OutVal}, Reports),
State2 = State#state{worker_reports=Reports2},
{noreply, State2};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(tick, State) ->
schedule_tick(),
State2 = tick(State),
{noreply, State2};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
schedule_tick() ->
erlang:send_after(1000, self(), tick).
tick(State=#state{stats_ets=StatsETS,
left_60s=Left60,
next_stats_60s=Next60,
stats_total=Total}) ->
{Usage, In, Out} = combine_reports(State),
Rejected = ets:update_counter(StatsETS, rejected, 0),
ets:update_counter(StatsETS, rejected, {2,-Rejected,0,0}),
NewNext60 = sidejob_stat:add(Rejected, In, Out, Next60),
NewTotal = sidejob_stat:add(Rejected, In, Out, Total),
State2 = State#state{usage=Usage,
rejected=Rejected,
in=In,
out=Out,
next_stats_60s=NewNext60,
stats_total=NewTotal},
State3 = case Left60 of
0 ->
State2#state{left_60s=59,
stats_60s=NewNext60,
next_stats_60s=sidejob_stat:new()};
_ ->
State2#state{left_60s=Left60-1}
end,
ets:insert(StatsETS, [{usage, Usage},
{stats, compute(State3)}]),
State3.
combine_reports(#state{worker_reports=Reports}) ->
dict:fold(fun(_, {Usage, In, Out}, {UsageAcc, InAcc, OutAcc}) ->
{UsageAcc + Usage, InAcc + In, OutAcc + Out}
end, {0,0,0}, Reports).
compute(#state{usage=Usage, rejected=Rejected, in=In, out=Out,
stats_60s=Stats60s, stats_total=StatsTotal}) ->
{Usage60, Rejected60, InAvg60, InMax60, OutAvg60, OutMax60} =
sidejob_stat:compute(Stats60s),
{UsageTot, RejectedTot, InAvgTot, InMaxTot, OutAvgTot, OutMaxTot} =
sidejob_stat:compute(StatsTotal),
[{usage, Usage},
{rejected, Rejected},
{in_rate, In},
{out_rate, Out},
{usage_60s, Usage60},
{rejected_60s, Rejected60},
{avg_in_rate_60s, InAvg60},
{max_in_rate_60s, InMax60},
{avg_out_rate_60s, OutAvg60},
{max_out_rate_60s, OutMax60},
{usage_total, UsageTot},
{rejected_total, RejectedTot},
{avg_in_rate_total, InAvgTot},
{max_in_rate_total, InMaxTot},
{avg_out_rate_total, OutAvgTot},
{max_out_rate_total, OutMaxTot}].
|
e4ceae113c5cd81243285e9b555c6cc06f8c3938ce42763289cd32af60760b8c | ghcjs/jsaddle-dom | OESVertexArrayObject.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.OESVertexArrayObject
(createVertexArrayOES, createVertexArrayOES_, deleteVertexArrayOES,
isVertexArrayOES, isVertexArrayOES_, bindVertexArrayOES,
pattern VERTEX_ARRAY_BINDING_OES, OESVertexArrayObject(..),
gTypeOESVertexArrayObject)
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
| < -US/docs/Web/API/OESVertexArrayObject.createVertexArrayOES Mozilla OESVertexArrayObject.createVertexArrayOES documentation >
createVertexArrayOES ::
(MonadDOM m) => OESVertexArrayObject -> m WebGLVertexArrayObjectOES
createVertexArrayOES self
= liftDOM
((self ^. jsf "createVertexArrayOES" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/OESVertexArrayObject.createVertexArrayOES Mozilla OESVertexArrayObject.createVertexArrayOES documentation >
createVertexArrayOES_ ::
(MonadDOM m) => OESVertexArrayObject -> m ()
createVertexArrayOES_ self
= liftDOM (void (self ^. jsf "createVertexArrayOES" ()))
| < -US/docs/Web/API/OESVertexArrayObject.deleteVertexArrayOES Mozilla OESVertexArrayObject.deleteVertexArrayOES documentation >
deleteVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
deleteVertexArrayOES self arrayObject
= liftDOM
(void (self ^. jsf "deleteVertexArrayOES" [toJSVal arrayObject]))
| < -US/docs/Web/API/OESVertexArrayObject.isVertexArrayOES Mozilla OESVertexArrayObject.isVertexArrayOES documentation >
isVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m Bool
isVertexArrayOES self arrayObject
= liftDOM
((self ^. jsf "isVertexArrayOES" [toJSVal arrayObject]) >>=
valToBool)
| < -US/docs/Web/API/OESVertexArrayObject.isVertexArrayOES Mozilla OESVertexArrayObject.isVertexArrayOES documentation >
isVertexArrayOES_ ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
isVertexArrayOES_ self arrayObject
= liftDOM
(void (self ^. jsf "isVertexArrayOES" [toJSVal arrayObject]))
| < -US/docs/Web/API/OESVertexArrayObject.bindVertexArrayOES Mozilla OESVertexArrayObject.bindVertexArrayOES documentation >
bindVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
bindVertexArrayOES self arrayObject
= liftDOM
(void (self ^. jsf "bindVertexArrayOES" [toJSVal arrayObject]))
pattern VERTEX_ARRAY_BINDING_OES = 34229
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/OESVertexArrayObject.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.OESVertexArrayObject
(createVertexArrayOES, createVertexArrayOES_, deleteVertexArrayOES,
isVertexArrayOES, isVertexArrayOES_, bindVertexArrayOES,
pattern VERTEX_ARRAY_BINDING_OES, OESVertexArrayObject(..),
gTypeOESVertexArrayObject)
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
| < -US/docs/Web/API/OESVertexArrayObject.createVertexArrayOES Mozilla OESVertexArrayObject.createVertexArrayOES documentation >
createVertexArrayOES ::
(MonadDOM m) => OESVertexArrayObject -> m WebGLVertexArrayObjectOES
createVertexArrayOES self
= liftDOM
((self ^. jsf "createVertexArrayOES" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/OESVertexArrayObject.createVertexArrayOES Mozilla OESVertexArrayObject.createVertexArrayOES documentation >
createVertexArrayOES_ ::
(MonadDOM m) => OESVertexArrayObject -> m ()
createVertexArrayOES_ self
= liftDOM (void (self ^. jsf "createVertexArrayOES" ()))
| < -US/docs/Web/API/OESVertexArrayObject.deleteVertexArrayOES Mozilla OESVertexArrayObject.deleteVertexArrayOES documentation >
deleteVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
deleteVertexArrayOES self arrayObject
= liftDOM
(void (self ^. jsf "deleteVertexArrayOES" [toJSVal arrayObject]))
| < -US/docs/Web/API/OESVertexArrayObject.isVertexArrayOES Mozilla OESVertexArrayObject.isVertexArrayOES documentation >
isVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m Bool
isVertexArrayOES self arrayObject
= liftDOM
((self ^. jsf "isVertexArrayOES" [toJSVal arrayObject]) >>=
valToBool)
| < -US/docs/Web/API/OESVertexArrayObject.isVertexArrayOES Mozilla OESVertexArrayObject.isVertexArrayOES documentation >
isVertexArrayOES_ ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
isVertexArrayOES_ self arrayObject
= liftDOM
(void (self ^. jsf "isVertexArrayOES" [toJSVal arrayObject]))
| < -US/docs/Web/API/OESVertexArrayObject.bindVertexArrayOES Mozilla OESVertexArrayObject.bindVertexArrayOES documentation >
bindVertexArrayOES ::
(MonadDOM m) =>
OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
bindVertexArrayOES self arrayObject
= liftDOM
(void (self ^. jsf "bindVertexArrayOES" [toJSVal arrayObject]))
pattern VERTEX_ARRAY_BINDING_OES = 34229
|
28121c8654d36abb6ee72c77220e0de211aeda71d5384bbe50acecb8fda3dc8b | sru-systems/protobuf-simple | WireTag.hs | -- |
Module : Data . ProtoBuf . WireTag
Copyright : ( c ) 2015 - 2016 < >
License : MIT
Maintainer : < >
--
WireTag type and functions .
module Data.ProtoBuf.WireTag
( WireTag(..)
, fromWireTag
, toWireTag
) where
import Data.Bits ((.|.))
import Data.ProtoBuf.FieldNumber (fromFieldNumber, toFieldNumber, FieldNumber)
import Data.ProtoBuf.WireType (fromWireType, toWireType, WireType)
import Data.Word (Word32)
-- | Type to represent a wire tag.
data WireTag = WireTag FieldNumber WireType
deriving (Show, Eq, Ord)
| Convert a WireTag into a Word32 .
fromWireTag :: WireTag -> Word32
fromWireTag (WireTag fn wt) = fromFieldNumber fn .|. fromWireType wt
| Convert a Word32 into a WireTag or an error .
toWireTag :: Word32 -> Either String WireTag
toWireTag i = do
fieldNumber <- toFieldNumber i
wireType <- toWireType i
return $ WireTag fieldNumber wireType
| null | https://raw.githubusercontent.com/sru-systems/protobuf-simple/8d19dfc68466c1ce69e9d3af6e75df16fffd32cc/src/Data/ProtoBuf/WireTag.hs | haskell | |
| Type to represent a wire tag. | Module : Data . ProtoBuf . WireTag
Copyright : ( c ) 2015 - 2016 < >
License : MIT
Maintainer : < >
WireTag type and functions .
module Data.ProtoBuf.WireTag
( WireTag(..)
, fromWireTag
, toWireTag
) where
import Data.Bits ((.|.))
import Data.ProtoBuf.FieldNumber (fromFieldNumber, toFieldNumber, FieldNumber)
import Data.ProtoBuf.WireType (fromWireType, toWireType, WireType)
import Data.Word (Word32)
data WireTag = WireTag FieldNumber WireType
deriving (Show, Eq, Ord)
| Convert a WireTag into a Word32 .
fromWireTag :: WireTag -> Word32
fromWireTag (WireTag fn wt) = fromFieldNumber fn .|. fromWireType wt
| Convert a Word32 into a WireTag or an error .
toWireTag :: Word32 -> Either String WireTag
toWireTag i = do
fieldNumber <- toFieldNumber i
wireType <- toWireType i
return $ WireTag fieldNumber wireType
|
1ad1af84e03138e7e8798800ab46700d666f376692846a831daffaf67388994f | lolepezy/rpki-prover | TestTypes.hs | module RPKI.TestTypes where
import RPKI.Config
testConfig :: Config
testConfig = defaultConfig | null | https://raw.githubusercontent.com/lolepezy/rpki-prover/17b4381a57eee3772ea1299cf387562f2e5ad477/test/src/RPKI/TestTypes.hs | haskell | module RPKI.TestTypes where
import RPKI.Config
testConfig :: Config
testConfig = defaultConfig | |
61f4a60bed17b467d6af3cc76fb2bd2c8d6523e2371a08721a7370fff6f37dbb | xnning/haskell-programming-from-first-principles | Addition.hs | module Addition where
import Test.Hspec
import Test.QuickCheck
prop_additionGreater :: Int -> Bool
prop_additionGreater x = x + 1 > x
runQc :: IO ()
runQc = quickCheck prop_additionGreater
main :: IO ()
main = hspec $ do
describe "Addition" $ do
it "1 + 1 is greater than 1" $ do
property $ \x -> x + 1 > (x :: Int)
genBool :: Gen Bool
genBool = choose (True, False)
genBool' :: Gen Bool
genBool' = elements [False, True]
genOrdering :: Gen Ordering
genOrdering = elements [LT, EQ, GT]
genChar :: Gen Char
genChar = elements ['a' .. 'z']
genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b)
genTuple = do
a <- arbitrary
b <- arbitrary
return (a, b)
genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (a, b, c)
genThreeple = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return (a, b, c)
genEither :: (Arbitrary a, Arbitrary b) => Gen (Either a b)
genEither = do
a <- arbitrary
b <- arbitrary
elements [Left a, Right b]
genMaybe :: Arbitrary a => Gen (Maybe a)
genMaybe = do
a <- arbitrary
elements [Nothing, Just a]
genMaybe' :: Arbitrary a => Gen (Maybe a)
genMaybe' = do
a <- arbitrary
frequency [(1, return Nothing), (3, return (Just a))]
| null | https://raw.githubusercontent.com/xnning/haskell-programming-from-first-principles/0c49f799cfb6bf2dc05fa1265af3887b795dc5a0/projs/test/Addition.hs | haskell | module Addition where
import Test.Hspec
import Test.QuickCheck
prop_additionGreater :: Int -> Bool
prop_additionGreater x = x + 1 > x
runQc :: IO ()
runQc = quickCheck prop_additionGreater
main :: IO ()
main = hspec $ do
describe "Addition" $ do
it "1 + 1 is greater than 1" $ do
property $ \x -> x + 1 > (x :: Int)
genBool :: Gen Bool
genBool = choose (True, False)
genBool' :: Gen Bool
genBool' = elements [False, True]
genOrdering :: Gen Ordering
genOrdering = elements [LT, EQ, GT]
genChar :: Gen Char
genChar = elements ['a' .. 'z']
genTuple :: (Arbitrary a, Arbitrary b) => Gen (a, b)
genTuple = do
a <- arbitrary
b <- arbitrary
return (a, b)
genThreeple :: (Arbitrary a, Arbitrary b, Arbitrary c) => Gen (a, b, c)
genThreeple = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return (a, b, c)
genEither :: (Arbitrary a, Arbitrary b) => Gen (Either a b)
genEither = do
a <- arbitrary
b <- arbitrary
elements [Left a, Right b]
genMaybe :: Arbitrary a => Gen (Maybe a)
genMaybe = do
a <- arbitrary
elements [Nothing, Just a]
genMaybe' :: Arbitrary a => Gen (Maybe a)
genMaybe' = do
a <- arbitrary
frequency [(1, return Nothing), (3, return (Just a))]
| |
89c628b6f1fbf31f16f9a75c75dbce913169b76351ead239a00931800b15f7f3 | BekaValentine/SimpleFP-v2 | Evaluation.hs | {-# OPTIONS -Wall #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
-- | This module defines how to evaluate terms in the dependently typed lambda
-- calculus.
module Quasiquote.Core.Evaluation where
import Control.Monad.Except
import Utils.ABT
import Utils.Env
import Utils.Eval
import Utils.Names
import Utils.Pretty
import Utils.Telescope
import Quasiquote.Core.Term
-- | Because a case expression can be evaluated under a binder, it's necessary
-- to determine when a match failure is real or illusory. For example, if we
have the function @\x - > case x of { Zero - > True ; _ - > False } @ , and
naively tried to match , the first clause would fail , because @x = /= Zero@ ,
and the second would succeed , reducing this function to @\x - > False@.
But this would be bad , because if we then applied this function to @Zero@ ,
the result is just But if we had applied the original function to
@Zero@ and evaluated , it would reduce to @True@. Instead , we need to know
-- more than just did the match succeed or fail, but rather, did it succeed,
-- definitely fail because of a constructor mismatch, or is it uncertain
-- because of insufficient information (e.g. a variable or some other
-- non-constructor expression). We can use this type to represent that
three - way distinction between definite matches , definite failures , and
-- unknown situations.
data MatchResult a
= Success a
| Unknown
| Failure
deriving (Functor)
instance Applicative MatchResult where
pure = Success
Success f <*> Success x = Success (f x)
Unknown <*> _ = Unknown
_ <*> Unknown = Unknown
_ <*> _ = Failure
instance Monad MatchResult where
return = Success
Success x >>= f = f x
Unknown >>= _ = Unknown
Failure >>= _ = Failure
-- | Pattern matching for case expressions.
matchPattern :: Pattern -> Term -> MatchResult [Term]
matchPattern (Var _) v = Success [v]
matchPattern (In (ConPat c ps)) (In (Con c' as))
| c == c' && length ps == length as =
fmap concat
$ forM (zip ps as)
$ \((plic,psc),(plic',asc)) ->
if (plic == plic')
then matchPattern (body psc) (body asc)
else Failure
| otherwise = Failure
matchPattern (In (AssertionPat _)) v = Success [v]
matchPattern _ _ = Unknown
matchPatterns :: [Pattern] -> [Term] -> MatchResult [Term]
matchPatterns [] [] =
Success []
matchPatterns (p:ps) (m:ms) =
do vs <- matchPattern p m
vs' <- matchPatterns ps ms
return $ vs ++ vs'
matchPatterns _ _ = Failure
matchClauses :: [Clause] -> [Term] -> MatchResult Term
matchClauses [] _ = Failure
matchClauses (Clause pscs sc:cs) ms =
case matchPatterns (map patternBody pscs) ms of
Failure -> matchClauses cs ms
Unknown -> Unknown
Success vs -> Success (instantiate sc vs)
-- | Standard eager evaluation.
type EnvKey = (String,String)
instance ParamEval Int (Env EnvKey Term) Term where
paramEval _ (Var v) =
return $ Var v
paramEval 0 (In (Defined (Absolute m n))) =
do env <- environment
case lookup (m,n) env of
Nothing -> throwError $ "Unknown constant/defined term: "
++ showName (Absolute m n)
Just x -> paramEval 0 x
paramEval _ (In (Defined (Absolute m n))) =
return $ In (Defined (Absolute m n))
paramEval _ (In (Defined x)) =
throwError $ "Cannot evaluate the local name " ++ showName x
paramEval 0 (In (Ann m _)) =
paramEval 0 (instantiate0 m)
paramEval l (In (Ann m t)) =
do em <- paramEval l (instantiate0 m)
et <- paramEval l (instantiate0 t)
return $ annH em et
paramEval _ (In Type) =
return $ In Type
paramEval l (In (Fun plic a sc)) =
do ea <- underF (paramEval l) a
esc <- underF (paramEval l) sc
return $ In (Fun plic ea esc)
paramEval l (In (Lam plic sc)) =
do esc <- underF (paramEval l) sc
return $ In (Lam plic esc)
paramEval 0 (In (App plic f a)) =
do ef <- paramEval 0 (instantiate0 f)
ea <- paramEval 0 (instantiate0 a)
case ef of
In (Lam plic' sc)
| plic == plic' -> paramEval 0 (instantiate sc [ea])
| otherwise ->
throwError "Mismatching plicities."
_ -> return $ appH plic ef ea
paramEval l (In (App plic f a)) =
do ef <- paramEval l (instantiate0 f)
ea <- paramEval l (instantiate0 a)
return $ appH plic ef ea
paramEval l (In (Con c as)) =
do eas <- forM as $ \(plic,a) ->
do ea <- paramEval l (instantiate0 a)
return (plic,ea)
return $ conH c eas
paramEval 0 (In (Case ms mot cs)) =
do ems <- mapM (paramEval 0) (map instantiate0 ms)
case matchClauses cs ems of
Success b -> paramEval 0 b
Unknown ->
do emot <- paramEval 0 mot
return $ caseH ems emot cs
Failure ->
throwError $ "Incomplete pattern match: "
++ pretty (In (Case ms mot cs))
paramEval l (In (Case ms mot cs)) =
do ems <- mapM (paramEval l) (map instantiate0 ms)
emot <- paramEval l mot
ecs <- if l == 0
then return cs
else mapM (paramEval l) cs
return $ caseH ems emot ecs
paramEval l (In (RecordType fields (Telescope ascs))) =
do eascs <- mapM (underF (paramEval l)) ascs
return $ In (RecordType fields (Telescope eascs))
paramEval l (In (RecordCon fields)) =
do fields' <- forM fields $ \(f,m) -> do
em <- paramEval l (instantiate0 m)
return (f,em)
return $ recordConH fields'
paramEval 0 (In (RecordProj r x)) =
do em <- paramEval 0 (instantiate0 r)
case em of
In (RecordCon fields) ->
case lookup x fields of
Nothing ->
throwError $ "Unknown field '" ++ x ++ "' in record "
++ pretty em
Just m' ->
return $ instantiate0 m'
_ ->
return $ recordProjH em x
paramEval l (In (RecordProj r x)) =
do em <- paramEval l (instantiate0 r)
return $ recordProjH em x
paramEval l (In (QuotedType a)) =
do ea <- paramEval l (instantiate0 a)
return $ quotedTypeH ea
paramEval l (In (Quote m)) =
do em <- paramEval (l+1) (instantiate0 m)
return $ quoteH em
paramEval 0 (In (Unquote _)) =
throwError $ "Cannot evaluate an unquote at level 0. "
++ "No such term should exist."
paramEval 1 (In (Unquote m)) =
do em <- paramEval 0 (instantiate0 m)
case em of
In (Quote m') -> return (instantiate0 m')
_ -> return $ unquoteH em
paramEval l (In (Unquote m)) =
do em <- paramEval (l-1) (instantiate0 m)
return $ unquoteH em
instance ParamEval Int (Env EnvKey Term) CaseMotive where
paramEval l (CaseMotive (BindingTelescope ascs bsc)) =
do eascs <- mapM (underF (paramEval l)) ascs
ebsc <- underF (paramEval l) bsc
return $ CaseMotive (BindingTelescope eascs ebsc)
instance ParamEval Int (Env EnvKey Term) Clause where
paramEval l (Clause pscs bsc) =
do epscs <- mapM (paramEval l) pscs
ebsc <- underF (paramEval l) bsc
return $ Clause epscs ebsc
instance ParamEval Int (Env EnvKey Term) (PatternF (Scope TermF)) where
paramEval l (PatternF x) =
do ex <- underF (paramEval l) x
return $ PatternF ex
instance ParamEval Int (Env EnvKey Term) (ABT (PatternFF (Scope TermF))) where
paramEval _ (Var v) =
return $ Var v
paramEval l (In (ConPat c ps)) =
do eps <- forM ps $ \(plic,p) ->
do ep <- underF (paramEval l) p
return (plic,ep)
return $ In (ConPat c eps)
paramEval l (In (AssertionPat m)) =
do em <- underF (paramEval l) m
return $ In (AssertionPat em)
paramEval _ (In MakeMeta) =
return $ In MakeMeta | null | https://raw.githubusercontent.com/BekaValentine/SimpleFP-v2/ae00ec809caefcd13664395b0ae2fc66145f6a74/src/Quasiquote/Core/Evaluation.hs | haskell | # OPTIONS -Wall #
# LANGUAGE TypeSynonymInstances #
| This module defines how to evaluate terms in the dependently typed lambda
calculus.
| Because a case expression can be evaluated under a binder, it's necessary
to determine when a match failure is real or illusory. For example, if we
more than just did the match succeed or fail, but rather, did it succeed,
definitely fail because of a constructor mismatch, or is it uncertain
because of insufficient information (e.g. a variable or some other
non-constructor expression). We can use this type to represent that
unknown situations.
| Pattern matching for case expressions.
| Standard eager evaluation. | # LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Quasiquote.Core.Evaluation where
import Control.Monad.Except
import Utils.ABT
import Utils.Env
import Utils.Eval
import Utils.Names
import Utils.Pretty
import Utils.Telescope
import Quasiquote.Core.Term
have the function @\x - > case x of { Zero - > True ; _ - > False } @ , and
naively tried to match , the first clause would fail , because @x = /= Zero@ ,
and the second would succeed , reducing this function to @\x - > False@.
But this would be bad , because if we then applied this function to @Zero@ ,
the result is just But if we had applied the original function to
@Zero@ and evaluated , it would reduce to @True@. Instead , we need to know
three - way distinction between definite matches , definite failures , and
data MatchResult a
= Success a
| Unknown
| Failure
deriving (Functor)
instance Applicative MatchResult where
pure = Success
Success f <*> Success x = Success (f x)
Unknown <*> _ = Unknown
_ <*> Unknown = Unknown
_ <*> _ = Failure
instance Monad MatchResult where
return = Success
Success x >>= f = f x
Unknown >>= _ = Unknown
Failure >>= _ = Failure
matchPattern :: Pattern -> Term -> MatchResult [Term]
matchPattern (Var _) v = Success [v]
matchPattern (In (ConPat c ps)) (In (Con c' as))
| c == c' && length ps == length as =
fmap concat
$ forM (zip ps as)
$ \((plic,psc),(plic',asc)) ->
if (plic == plic')
then matchPattern (body psc) (body asc)
else Failure
| otherwise = Failure
matchPattern (In (AssertionPat _)) v = Success [v]
matchPattern _ _ = Unknown
matchPatterns :: [Pattern] -> [Term] -> MatchResult [Term]
matchPatterns [] [] =
Success []
matchPatterns (p:ps) (m:ms) =
do vs <- matchPattern p m
vs' <- matchPatterns ps ms
return $ vs ++ vs'
matchPatterns _ _ = Failure
matchClauses :: [Clause] -> [Term] -> MatchResult Term
matchClauses [] _ = Failure
matchClauses (Clause pscs sc:cs) ms =
case matchPatterns (map patternBody pscs) ms of
Failure -> matchClauses cs ms
Unknown -> Unknown
Success vs -> Success (instantiate sc vs)
type EnvKey = (String,String)
instance ParamEval Int (Env EnvKey Term) Term where
paramEval _ (Var v) =
return $ Var v
paramEval 0 (In (Defined (Absolute m n))) =
do env <- environment
case lookup (m,n) env of
Nothing -> throwError $ "Unknown constant/defined term: "
++ showName (Absolute m n)
Just x -> paramEval 0 x
paramEval _ (In (Defined (Absolute m n))) =
return $ In (Defined (Absolute m n))
paramEval _ (In (Defined x)) =
throwError $ "Cannot evaluate the local name " ++ showName x
paramEval 0 (In (Ann m _)) =
paramEval 0 (instantiate0 m)
paramEval l (In (Ann m t)) =
do em <- paramEval l (instantiate0 m)
et <- paramEval l (instantiate0 t)
return $ annH em et
paramEval _ (In Type) =
return $ In Type
paramEval l (In (Fun plic a sc)) =
do ea <- underF (paramEval l) a
esc <- underF (paramEval l) sc
return $ In (Fun plic ea esc)
paramEval l (In (Lam plic sc)) =
do esc <- underF (paramEval l) sc
return $ In (Lam plic esc)
paramEval 0 (In (App plic f a)) =
do ef <- paramEval 0 (instantiate0 f)
ea <- paramEval 0 (instantiate0 a)
case ef of
In (Lam plic' sc)
| plic == plic' -> paramEval 0 (instantiate sc [ea])
| otherwise ->
throwError "Mismatching plicities."
_ -> return $ appH plic ef ea
paramEval l (In (App plic f a)) =
do ef <- paramEval l (instantiate0 f)
ea <- paramEval l (instantiate0 a)
return $ appH plic ef ea
paramEval l (In (Con c as)) =
do eas <- forM as $ \(plic,a) ->
do ea <- paramEval l (instantiate0 a)
return (plic,ea)
return $ conH c eas
paramEval 0 (In (Case ms mot cs)) =
do ems <- mapM (paramEval 0) (map instantiate0 ms)
case matchClauses cs ems of
Success b -> paramEval 0 b
Unknown ->
do emot <- paramEval 0 mot
return $ caseH ems emot cs
Failure ->
throwError $ "Incomplete pattern match: "
++ pretty (In (Case ms mot cs))
paramEval l (In (Case ms mot cs)) =
do ems <- mapM (paramEval l) (map instantiate0 ms)
emot <- paramEval l mot
ecs <- if l == 0
then return cs
else mapM (paramEval l) cs
return $ caseH ems emot ecs
paramEval l (In (RecordType fields (Telescope ascs))) =
do eascs <- mapM (underF (paramEval l)) ascs
return $ In (RecordType fields (Telescope eascs))
paramEval l (In (RecordCon fields)) =
do fields' <- forM fields $ \(f,m) -> do
em <- paramEval l (instantiate0 m)
return (f,em)
return $ recordConH fields'
paramEval 0 (In (RecordProj r x)) =
do em <- paramEval 0 (instantiate0 r)
case em of
In (RecordCon fields) ->
case lookup x fields of
Nothing ->
throwError $ "Unknown field '" ++ x ++ "' in record "
++ pretty em
Just m' ->
return $ instantiate0 m'
_ ->
return $ recordProjH em x
paramEval l (In (RecordProj r x)) =
do em <- paramEval l (instantiate0 r)
return $ recordProjH em x
paramEval l (In (QuotedType a)) =
do ea <- paramEval l (instantiate0 a)
return $ quotedTypeH ea
paramEval l (In (Quote m)) =
do em <- paramEval (l+1) (instantiate0 m)
return $ quoteH em
paramEval 0 (In (Unquote _)) =
throwError $ "Cannot evaluate an unquote at level 0. "
++ "No such term should exist."
paramEval 1 (In (Unquote m)) =
do em <- paramEval 0 (instantiate0 m)
case em of
In (Quote m') -> return (instantiate0 m')
_ -> return $ unquoteH em
paramEval l (In (Unquote m)) =
do em <- paramEval (l-1) (instantiate0 m)
return $ unquoteH em
instance ParamEval Int (Env EnvKey Term) CaseMotive where
paramEval l (CaseMotive (BindingTelescope ascs bsc)) =
do eascs <- mapM (underF (paramEval l)) ascs
ebsc <- underF (paramEval l) bsc
return $ CaseMotive (BindingTelescope eascs ebsc)
instance ParamEval Int (Env EnvKey Term) Clause where
paramEval l (Clause pscs bsc) =
do epscs <- mapM (paramEval l) pscs
ebsc <- underF (paramEval l) bsc
return $ Clause epscs ebsc
instance ParamEval Int (Env EnvKey Term) (PatternF (Scope TermF)) where
paramEval l (PatternF x) =
do ex <- underF (paramEval l) x
return $ PatternF ex
instance ParamEval Int (Env EnvKey Term) (ABT (PatternFF (Scope TermF))) where
paramEval _ (Var v) =
return $ Var v
paramEval l (In (ConPat c ps)) =
do eps <- forM ps $ \(plic,p) ->
do ep <- underF (paramEval l) p
return (plic,ep)
return $ In (ConPat c eps)
paramEval l (In (AssertionPat m)) =
do em <- underF (paramEval l) m
return $ In (AssertionPat em)
paramEval _ (In MakeMeta) =
return $ In MakeMeta |
09eda807dacdae326675998cf0b78a44646a5a5d040bf0721e3c9aed4a7d2da0 | oakes/edna | core.clj | (ns edna.core
(:require [alda.lisp]
[alda.sound :as sound]
[edna.parse :as parse]
[clojure.string :as str]
[alda.lisp.score :as als]
[alda.lisp.events :as ale]
[alda.lisp.attributes :as ala]
[alda.lisp.model.duration :as almd]
[alda.lisp.model.pitch :as almp]
[alda.sound.midi :as midi]
[clojure.java.io :as io]
[clojure.data.codec.base64 :as base64])
(:import [javax.sound.midi MidiSystem]
[javax.sound.sampled AudioSystem AudioFormat AudioFileFormat$Type]
[meico.midi Midi2AudioRenderer]
[meico.audio Audio]))
(def ^:private default-attrs {:octave 4 :length 1/4 :tempo 120
:pan 50 :quantize 90 :transpose 0
:volume 100 :parent-ids [] :play? true
:key-signature #{}})
(defmulti edna->alda*
"The underlying multimethod for converting edna to alda. You probably don't need to use this."
(fn [val parent-attrs] (first val)))
(defmethod edna->alda* :score [[_ {:keys [subscores] :as score}]
{:keys [sibling-id parent-ids] :as parent-attrs}]
(let [id (inc (or sibling-id 0))
{:keys [instrument] :as attrs} (merge parent-attrs (select-keys score [:instrument]))]
[(ale/part (if instrument (name instrument) {})
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(first
(reduce
(fn [[subscores attrs] subscore]
(let [attrs (assoc attrs :parent-ids
(conj parent-ids id))
[subscore attrs] (edna->alda* subscore attrs)]
[(conj subscores subscore) attrs]))
[[] (dissoc attrs :sibling-id)]
(vec subscores)))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :concurrent-score [[_ scores]
{:keys [sibling-id parent-ids] :as parent-attrs}]
(let [id (inc (or sibling-id 0))
instruments (map :instrument scores)]
(when (not= (count instruments) (count (set instruments)))
(throw (Exception. (str
"Can't use the same instrument "
"multiple times in the same set "
"(this limitation my change eventually)"))))
[(ale/part {}
(reduce
(fn [scores score]
(let [[score _] (edna->alda* [:score score] parent-attrs)]
(conj scores score)))
[]
(vec scores))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :attrs [[_ {:keys [note] :as attrs}] parent-attrs]
(if note
(let [[note {:keys [sibling-id]}] (edna->alda* [:note note] (merge parent-attrs attrs))]
[note (assoc parent-attrs :sibling-id sibling-id)])
[nil (merge parent-attrs attrs)]))
(defmethod edna->alda* :note [[_ note]
{:keys [instrument octave length tempo
pan quantize transpose volume
sibling-id parent-ids play?
key-signature]
:as parent-attrs}]
(when-not instrument
(throw (Exception. (str "Can't play " note " without specifying an instrument"))))
(if-not play?
[nil parent-attrs]
(let [id (inc (or sibling-id 0))
{:keys [note accidental octave-op octaves]} (parse/parse-note note)
note (keyword (str note))
accidental (parse/accidental->keyword accidental)
new-octave (cond
;; if the octave has a + or -, treat it as a relative octave change
octave-op
(-> (cons octave-op (or octaves [\1]))
str/join
Integer/valueOf
(+ octave))
;; if the octave is just a number, treat it as an absolute octave change
octaves
(-> octaves
str/join
Integer/valueOf)
;; if there is no octave in the note, use the existing octave
:else
octave)]
[(ale/part (name instrument)
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(ala/octave new-octave)
(ala/tempo tempo)
(ala/pan pan)
(ala/quantize quantize)
(ala/transpose transpose)
(ala/volume volume)
(ala/key-signature (reduce
(fn [m unparsed-note]
(let [{:keys [note accidental]} (parse/parse-note unparsed-note)
note (keyword (str note))
accidental (parse/accidental->keyword accidental)]
(cond
(contains? m note)
(throw (Exception. (str note " found more than once in " key-signature)))
(nil? accidental)
(throw (Exception. (str unparsed-note " from " key-signature
" should either have a # (sharp) or = (flat)")))
:else
(assoc m note [accidental]))))
{}
key-signature))
(ale/note
(or (some->> accidental (almp/pitch note))
(almp/pitch note))
(almd/duration (almd/note-length (/ 1 length))))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)])))
(defmethod edna->alda* :chord [[_ chord]
{:keys [instrument sibling-id parent-ids play?]
:as parent-attrs}]
(when-not instrument
(throw (Exception. (str "Can't play "
(set (map second chord))
" without specifying an instrument"))))
(if-not play?
[nil parent-attrs]
(let [id (inc (or sibling-id 0))
attrs (-> parent-attrs
(assoc :parent-ids (conj parent-ids id))
(dissoc :sibling-id))]
[(ale/part (name instrument)
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(apply ale/chord
(map (fn [note]
(first (edna->alda* note attrs)))
chord))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)])))
(defmethod edna->alda* :rest [[_ _] {:keys [length sibling-id parent-ids]
:as parent-attrs}]
(let [id (inc (or sibling-id 0))]
[[(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(ale/pause (almd/duration (almd/note-length (/ 1 length))))
(ale/marker (str/join "." (conj parent-ids id)))]
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :length [[_ length] parent-attrs]
[nil (assoc parent-attrs :length length)])
(defmethod edna->alda* :default [[subscore-name] parent-attrs]
(throw (Exception. (str subscore-name " not recognized"))))
(defn edna->alda
"Converts from edna to alda format."
[content]
(->> default-attrs
(edna->alda* (parse/parse content))
first))
(defn stop!
"Stops the given score from playing. The `score` should be what was returned by `play!`."
[score]
(some-> score sound/tear-down!)
nil)
(defn play!
"Takes edna content and plays it. Returns a score map, which can be used to stop it later."
[content]
(binding [midi/*midi-synth* (midi/new-midi-synth true)
sound/*use-midi-sequencer* false
sound/*play-opts* {:async? true
:one-off? true}]
(-> content edna->alda als/score sound/play! :score)))
(defmulti ^:private export!*
(fn [content opts]
(:type opts)))
(defmethod export!* :midi [content {:keys [out]}]
(-> content edna->alda als/score sound/create-sequence!
(MidiSystem/write 0 out))
out)
(defmethod export!* :wav [content {:keys [out soundbank format]}]
(let [renderer (Midi2AudioRenderer.)
midi->input-stream #(.renderMidi2Audio renderer % soundbank format)]
(-> content edna->alda als/score sound/create-sequence!
midi->input-stream
(AudioSystem/write AudioFileFormat$Type/WAVE out)))
out)
(defmethod export!* :mp3 [content {:keys [out soundbank format]}]
(let [renderer (Midi2AudioRenderer.)
midi->input-stream #(.renderMidi2Audio renderer % soundbank format)]
(with-open [fos (if (instance? java.io.File out)
(java.io.FileOutputStream. out)
out)]
(.write fos
(-> content edna->alda als/score sound/create-sequence!
midi->input-stream
Audio/convertAudioInputStream2ByteArray
(Audio/encodePcmToMp3 format)))))
out)
(def ^:private default-soundbank (delay
(some-> (or ;; from org.bitbucket.daveyarwood/fluid-r3
(io/resource "fluid-r3.sf2")
;; from org.clojars.oakes/meico
(io/resource "Aspirin_160_GMGS_2015.sf2"))
MidiSystem/getSoundbank)))
(defn export!
"Takes edna content and exports it, returning the value of :out. The opts map can contain:
:type - :midi, :wav, or :mp3 (required)
:out - A java.io.OutputStream or java.io.File object
(optional, defaults to a ByteArrayOutputStream)
:soundbank - A javax.sound.midi.Soundbank object, or nil to use the JVM's built-in one
(optional, defaults to a soundbank included in this library)
:format - A javax.sound.sampled.AudioFormat object
(optional, defaults to one with 44100 Hz)
Note: If you want to use the sound font installed on your system, rather than the one
built into edna, include `:soundbank nil` in your opts map."
[content opts]
(binding [midi/*midi-synth* (midi/new-midi-synth false)
sound/*use-midi-sequencer* true
sound/*play-opts* {:async? false
:one-off? true}]
(export!* content
(-> opts
(update :out #(or % (java.io.ByteArrayOutputStream.)))
(update :soundbank #(if (contains? opts :soundbank) % @default-soundbank))
(update :format #(or % (AudioFormat. 44100 16 2 true false)))))))
(defn edna->data-uri
"Turns the edna content into a data URI for use in browsers. The opts map can contain:
:soundbank - A javax.sound.midi.Soundbank object, or nil to use the JVM's built-in one
(optional, defaults to a soundbank included in this library)
:format - A javax.sound.sampled.AudioFormat object
(optional, defaults to one with 44100 Hz)
Note: If you want to use the sound font installed on your system, rather than the one
built into edna, include `:soundbank nil` in your opts map."
([content]
(edna->data-uri content {}))
([content opts]
(str
"data:audio/mp3;base64,"
(-> (binding [*out* (java.io.StringWriter.)]
(->> (select-keys opts [:soundbank :format])
(merge {:type :mp3})
(export! content)))
.toByteArray
(base64/encode)
(String. "UTF-8")))))
| null | https://raw.githubusercontent.com/oakes/edna/ca1928cd4190047aec486d2bcdc54d8d5a8bbf06/src/edna/core.clj | clojure | if the octave has a + or -, treat it as a relative octave change
if the octave is just a number, treat it as an absolute octave change
if there is no octave in the note, use the existing octave
from org.bitbucket.daveyarwood/fluid-r3
from org.clojars.oakes/meico | (ns edna.core
(:require [alda.lisp]
[alda.sound :as sound]
[edna.parse :as parse]
[clojure.string :as str]
[alda.lisp.score :as als]
[alda.lisp.events :as ale]
[alda.lisp.attributes :as ala]
[alda.lisp.model.duration :as almd]
[alda.lisp.model.pitch :as almp]
[alda.sound.midi :as midi]
[clojure.java.io :as io]
[clojure.data.codec.base64 :as base64])
(:import [javax.sound.midi MidiSystem]
[javax.sound.sampled AudioSystem AudioFormat AudioFileFormat$Type]
[meico.midi Midi2AudioRenderer]
[meico.audio Audio]))
(def ^:private default-attrs {:octave 4 :length 1/4 :tempo 120
:pan 50 :quantize 90 :transpose 0
:volume 100 :parent-ids [] :play? true
:key-signature #{}})
(defmulti edna->alda*
"The underlying multimethod for converting edna to alda. You probably don't need to use this."
(fn [val parent-attrs] (first val)))
(defmethod edna->alda* :score [[_ {:keys [subscores] :as score}]
{:keys [sibling-id parent-ids] :as parent-attrs}]
(let [id (inc (or sibling-id 0))
{:keys [instrument] :as attrs} (merge parent-attrs (select-keys score [:instrument]))]
[(ale/part (if instrument (name instrument) {})
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(first
(reduce
(fn [[subscores attrs] subscore]
(let [attrs (assoc attrs :parent-ids
(conj parent-ids id))
[subscore attrs] (edna->alda* subscore attrs)]
[(conj subscores subscore) attrs]))
[[] (dissoc attrs :sibling-id)]
(vec subscores)))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :concurrent-score [[_ scores]
{:keys [sibling-id parent-ids] :as parent-attrs}]
(let [id (inc (or sibling-id 0))
instruments (map :instrument scores)]
(when (not= (count instruments) (count (set instruments)))
(throw (Exception. (str
"Can't use the same instrument "
"multiple times in the same set "
"(this limitation my change eventually)"))))
[(ale/part {}
(reduce
(fn [scores score]
(let [[score _] (edna->alda* [:score score] parent-attrs)]
(conj scores score)))
[]
(vec scores))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :attrs [[_ {:keys [note] :as attrs}] parent-attrs]
(if note
(let [[note {:keys [sibling-id]}] (edna->alda* [:note note] (merge parent-attrs attrs))]
[note (assoc parent-attrs :sibling-id sibling-id)])
[nil (merge parent-attrs attrs)]))
(defmethod edna->alda* :note [[_ note]
{:keys [instrument octave length tempo
pan quantize transpose volume
sibling-id parent-ids play?
key-signature]
:as parent-attrs}]
(when-not instrument
(throw (Exception. (str "Can't play " note " without specifying an instrument"))))
(if-not play?
[nil parent-attrs]
(let [id (inc (or sibling-id 0))
{:keys [note accidental octave-op octaves]} (parse/parse-note note)
note (keyword (str note))
accidental (parse/accidental->keyword accidental)
new-octave (cond
octave-op
(-> (cons octave-op (or octaves [\1]))
str/join
Integer/valueOf
(+ octave))
octaves
(-> octaves
str/join
Integer/valueOf)
:else
octave)]
[(ale/part (name instrument)
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(ala/octave new-octave)
(ala/tempo tempo)
(ala/pan pan)
(ala/quantize quantize)
(ala/transpose transpose)
(ala/volume volume)
(ala/key-signature (reduce
(fn [m unparsed-note]
(let [{:keys [note accidental]} (parse/parse-note unparsed-note)
note (keyword (str note))
accidental (parse/accidental->keyword accidental)]
(cond
(contains? m note)
(throw (Exception. (str note " found more than once in " key-signature)))
(nil? accidental)
(throw (Exception. (str unparsed-note " from " key-signature
" should either have a # (sharp) or = (flat)")))
:else
(assoc m note [accidental]))))
{}
key-signature))
(ale/note
(or (some->> accidental (almp/pitch note))
(almp/pitch note))
(almd/duration (almd/note-length (/ 1 length))))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)])))
(defmethod edna->alda* :chord [[_ chord]
{:keys [instrument sibling-id parent-ids play?]
:as parent-attrs}]
(when-not instrument
(throw (Exception. (str "Can't play "
(set (map second chord))
" without specifying an instrument"))))
(if-not play?
[nil parent-attrs]
(let [id (inc (or sibling-id 0))
attrs (-> parent-attrs
(assoc :parent-ids (conj parent-ids id))
(dissoc :sibling-id))]
[(ale/part (name instrument)
(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(apply ale/chord
(map (fn [note]
(first (edna->alda* note attrs)))
chord))
(ale/marker (str/join "." (conj parent-ids id))))
(assoc parent-attrs :sibling-id id)])))
(defmethod edna->alda* :rest [[_ _] {:keys [length sibling-id parent-ids]
:as parent-attrs}]
(let [id (inc (or sibling-id 0))]
[[(when sibling-id
(ale/at-marker (str/join "." (conj parent-ids sibling-id))))
(ale/pause (almd/duration (almd/note-length (/ 1 length))))
(ale/marker (str/join "." (conj parent-ids id)))]
(assoc parent-attrs :sibling-id id)]))
(defmethod edna->alda* :length [[_ length] parent-attrs]
[nil (assoc parent-attrs :length length)])
(defmethod edna->alda* :default [[subscore-name] parent-attrs]
(throw (Exception. (str subscore-name " not recognized"))))
(defn edna->alda
"Converts from edna to alda format."
[content]
(->> default-attrs
(edna->alda* (parse/parse content))
first))
(defn stop!
"Stops the given score from playing. The `score` should be what was returned by `play!`."
[score]
(some-> score sound/tear-down!)
nil)
(defn play!
"Takes edna content and plays it. Returns a score map, which can be used to stop it later."
[content]
(binding [midi/*midi-synth* (midi/new-midi-synth true)
sound/*use-midi-sequencer* false
sound/*play-opts* {:async? true
:one-off? true}]
(-> content edna->alda als/score sound/play! :score)))
(defmulti ^:private export!*
(fn [content opts]
(:type opts)))
(defmethod export!* :midi [content {:keys [out]}]
(-> content edna->alda als/score sound/create-sequence!
(MidiSystem/write 0 out))
out)
(defmethod export!* :wav [content {:keys [out soundbank format]}]
(let [renderer (Midi2AudioRenderer.)
midi->input-stream #(.renderMidi2Audio renderer % soundbank format)]
(-> content edna->alda als/score sound/create-sequence!
midi->input-stream
(AudioSystem/write AudioFileFormat$Type/WAVE out)))
out)
(defmethod export!* :mp3 [content {:keys [out soundbank format]}]
(let [renderer (Midi2AudioRenderer.)
midi->input-stream #(.renderMidi2Audio renderer % soundbank format)]
(with-open [fos (if (instance? java.io.File out)
(java.io.FileOutputStream. out)
out)]
(.write fos
(-> content edna->alda als/score sound/create-sequence!
midi->input-stream
Audio/convertAudioInputStream2ByteArray
(Audio/encodePcmToMp3 format)))))
out)
(def ^:private default-soundbank (delay
(io/resource "fluid-r3.sf2")
(io/resource "Aspirin_160_GMGS_2015.sf2"))
MidiSystem/getSoundbank)))
(defn export!
"Takes edna content and exports it, returning the value of :out. The opts map can contain:
:type - :midi, :wav, or :mp3 (required)
:out - A java.io.OutputStream or java.io.File object
(optional, defaults to a ByteArrayOutputStream)
:soundbank - A javax.sound.midi.Soundbank object, or nil to use the JVM's built-in one
(optional, defaults to a soundbank included in this library)
:format - A javax.sound.sampled.AudioFormat object
(optional, defaults to one with 44100 Hz)
Note: If you want to use the sound font installed on your system, rather than the one
built into edna, include `:soundbank nil` in your opts map."
[content opts]
(binding [midi/*midi-synth* (midi/new-midi-synth false)
sound/*use-midi-sequencer* true
sound/*play-opts* {:async? false
:one-off? true}]
(export!* content
(-> opts
(update :out #(or % (java.io.ByteArrayOutputStream.)))
(update :soundbank #(if (contains? opts :soundbank) % @default-soundbank))
(update :format #(or % (AudioFormat. 44100 16 2 true false)))))))
(defn edna->data-uri
"Turns the edna content into a data URI for use in browsers. The opts map can contain:
:soundbank - A javax.sound.midi.Soundbank object, or nil to use the JVM's built-in one
(optional, defaults to a soundbank included in this library)
:format - A javax.sound.sampled.AudioFormat object
(optional, defaults to one with 44100 Hz)
Note: If you want to use the sound font installed on your system, rather than the one
built into edna, include `:soundbank nil` in your opts map."
([content]
(edna->data-uri content {}))
([content opts]
(str
"data:audio/mp3;base64,"
(-> (binding [*out* (java.io.StringWriter.)]
(->> (select-keys opts [:soundbank :format])
(merge {:type :mp3})
(export! content)))
.toByteArray
(base64/encode)
(String. "UTF-8")))))
|
cc7d6be10ab48cab1b4afef0396515434194eb462db80b568b3df7b77f892a76 | aryx/lfs | motif.ml | (** PROSITE-like patterns in sequence, whose elements come from a sub-logic. *)
module type PARAM =
sig
val toks_match : Syntax.t_list (** Syntaxtic representation of the 'match' prefix symbol. *)
val toks_begin : Syntax.t_list (** Syntactic representation of the 'begin' symbol. *)
val toks_end : Syntax.t_list (** Syntactic representation of the 'end' symbol. *)
val toks_sep : Syntax.t_list (** Syntactic representation of the element separator symbol. *)
val toks_any : Syntax.t_list (** Syntactic representation of the 'any element' symbol. *)
val feat_length : bool (** Whether to generate motif lengths as features. *)
val feat_dist : bool (** Whether to generate distribution of elements as features. *)
val feat_atoms : bool (** Whether to generate atom featues. *)
val gen_floating : bool (** True if 'begin' and 'end' are not compulsory in motifs generated by [gen]. *)
val gen_len : bool (** Whether to allow [gen] to generate features about the lengths. *)
* Condition to be verified on gaps / links in motifs : the 1st/3rd argument respectively tells whether the left / right element is begin / end .
val gen_min_xs : int (** Threshold number of generated motifs by [gen]. *)
end
module Make (Param : PARAM) (A : Logic.T) =
A.gen must satisfy : A.gen(f , , _ ) = { x } , and A.gen(f , g , A.gen(f , ) ) is empty
struct
include Logic.Default
module IntervParam = struct let verbose = true end
module Len = Openinterval.DotDot(Intpow.Make)
module Dist = Openinterval.DotDot(Floatpow.Make)
type e = int * int
(* interval for elastic segments *)
type a = Begin | Atom of A.t | Elastic of e | End
type t = Match of (bool * a list * bool * string)
| Len of Len.t
| Dist of (A.t * Dist.t) option
(* private functions *)
let print_debug s =
print_endline s;
flush stderr
let a_entails a1 a2 =
match a1, a2 with
| Begin, Begin -> true
| End, End -> true
| Atom x1, Atom x2 -> A.entails x1 x2
| _, _ -> false
let e_contains (min1,max1) (min2,max2) = min1 <= min2 & max2 <= max1
let e_append (min1,max1) (min2,max2) = (min1+min2, max1+max2)
let e_union (min1,max1) (min2,max2) = (min min1 min2, max max1 max2)
let rec get_length l =
let min, max = get_len2 l in
Len.parse (Syntax.of_list
(Token.Ident "in" :: Token.Nat min :: Token.Dot :: Token.Dot :: Token.Nat max :: []))
and get_len2 =
function
| [] -> 0, 0
| Begin::l -> get_len2 l
| End::_ -> 0, 0
| Atom _::l -> let min, max = get_len2 l in min+1, max+1
| Elastic (min,max)::l -> let min', max' = get_len2 l in min+min', max+max'
let rec get_dist a l =
let round x = floor (1000. *. x) /. 1000. in
let (xmin, ymin), (xmax, ymax) = get_dist2 a l in
let dmin = round (float xmin /. float ymin) in
let dmax = round (float xmax /. float ymax) in
Dist.parse (Syntax.of_list (Token.Ident "in" :: Syntax.toks_of_float (dmin,-3) @ Token.Dot :: Token.Dot :: Syntax.toks_of_float (dmax,-3)))
and get_dist2 a =
function
| [] -> (0,0), (0,0)
| Begin::l -> get_dist2 a l
| End::_ -> (0,0), (0,0)
| Atom a'::l ->
let (xmin,ymin), (xmax,ymax) = get_dist2 a l in
if A.entails a' a
then (xmin+1,ymin+1), (xmax+1,ymax+1)
else (xmin,ymin+1), (xmax,ymax+1)
| Elastic (min,max)::l ->
let (xmin,ymin), (xmax,ymax) = get_dist2 a l in
(xmin,ymin+max), (xmax+max,ymax+max)
(* public functions *)
open Token
let rec motif_cons n x xs =
if n <= 0
then xs
else motif_cons (n-1) x
( match x, xs with
| Begin, Begin::_ -> xs
| Begin, _ -> Begin::xs
| End, _ -> [End]
| Atom a, _ -> Atom a::xs
| Elastic (min,max), Elastic (min',max')::xs' -> Elastic (min+min',max+max')::xs'
| Elastic e, _ -> Elastic e::xs)
let motif_append m1 m2 =
List.fold_right (motif_cons 1) m1 m2
let print_e = function
| ( 0,1 ) - > [ ]
| (0,1) -> [Interro]
*)
| (1,1) -> []
| (min,max) ->
if max = min
then [LeftPar; Nat min; RightPar]
else [LeftPar; Nat min; Comma; Nat max; RightPar]
let rec print_seq = function
| l -> print_seq_loop true l
and print_seq_loop first_atom = function
| [] -> []
| Begin::l -> Param.toks_begin @ print_seq_loop true l
| End::l -> Param.toks_end @ print_seq_loop true l
| x::l -> print_seq_sep first_atom @ print_atom x @ print_seq_loop false l
and print_seq_sep first_atom =
if first_atom
then []
else Param.toks_sep
and print_atom = function
| Atom a -> A.print a
| Elastic e -> Param.toks_any @ print_e e
| _ -> assert false
let print_comment = function
| "" -> []
| c -> [Colon; String c]
let print = function
| Match (_,l,_, c) -> Param.toks_match @ print_seq l @ print_comment c
| Len length -> Ident "length" :: PP_tilda :: Len.print length
| Dist None -> [Ident "dist"]
| Dist (Some (a,d)) -> Ident "dist" :: PP_tilda :: A.print a @ PP_tilda :: Dist.print d
let parse_repeat = parser
| [<'LeftPar; 'Nat n; 'RightPar>] -> n
| [<>] -> 1
let parse_e = parser
| [<'LeftPar;
'Nat min ?? "Syntax error: positive integer expected in motif gap, after '('";
str
>] ->
( match str with parser
| [<'RightPar>] -> (min,min)
| [<'Comma;
'Nat max when max >= min ?? "Syntax error: integer expected in motif gap, after: " ^ Syntax.stringizer [LeftPar; Nat min; Comma];
'RightPar ?? "Syntax error: missing ')' in motif gap, after: " ^ Syntax.stringizer [LeftPar; Nat min; Comma; Nat max]
>] -> (min,max)
| [<>] -> raise (Stream.Error ("Syntax error: ')' or ',' expected after: " ^ Syntax.stringizer [LeftPar; Nat min]))
)
| [<>] -> (1,1)
| [ < ' > ] - > ( 0,1 )
| [<'Interro>] -> (0,1)
*)
let rec parse_seq = parser
| [<_ = Syntax.parse_tokens Param.toks_begin;
l, e = parse_seq_loop1 ?? "Syntax error: motif element, gap or end expected after: " ^ Syntax.stringizer Param.toks_begin
>] -> true, motif_cons 1 Begin l, e
| [<l, e = parse_seq_loop1>] -> false, l, e
| [<>] -> false, [], false
and parse_seq_loop1 = parser
| [<_ = Syntax.parse_tokens Param.toks_end>] ->
[End], true
| [<_ = Syntax.parse_tokens Param.toks_any;
elast = parse_e;
l, e = parse_seq_loop2
>] ->
motif_cons 1 (Elastic elast) l, e
| [<a, _ = parse_atom; (*n = parse_repeat;*)
l, e = parse_seq_loop2
>] ->
motif_cons 1 a l, e
| [<>] -> [], false
and parse_seq_loop2 = parser
| [<_ = Syntax.parse_tokens Param.toks_end>] -> [End], true
| [<_ = Syntax.parse_tokens Param.toks_sep;
l, e = parse_seq_loop1 ?? "Syntax error: motif element, gap or end expected after: " ^ Syntax.stringizer Param.toks_sep
>] -> l, e
| [<>] -> [], false
and parse_seq_is = parser
| [<x, a = parse_atom; (*n = parse_repeat;*)
l = parse_seq_is ?? "Syntax error: motif element expected after: " ^ Syntax.stringizer (A.print a)
>] -> motif_cons 1 x l
| [<>] -> [End]
and parse_atom = parser
| [<a = A.parse>] ->
if try A.entails (A.top ()) a with Not_found -> false
then Elastic (1,1), a
else Atom a, a
let parse_comment = parser
| [<'Colon; 'String c>] -> c
| [<>] -> ""
let parse = parser
| [<'Ident l when l.[0] = 'l';
length = Len.parse ?? "Syntax error in motif after '" ^ l ^ "'"
>] -> Len length
| [<'Ident d when d.[0] = 'd'; str>] -> (match str with parser
| [<a = A.parse;
d = Dist.parse ?? "Syntax error in motif after: " ^ Syntax.stringizer (Ident d :: A.print a)
>] -> Dist (Some (a,d))
| [<>] -> Dist None)
| [<'Ident "is";
toks = A.parse_compact ?? "Syntax error after 'is'";
c = parse_comment
>] -> Match (true, Begin::parse_seq_is (Syntax.of_list toks), true, c)
| [<b, l, e = Syntax.parse_tokens_and Param.toks_match parse_seq;
c = parse_comment
>] -> Match (b,l,e,c)
let rec simpl = function
| Match (b,l,e, c) ->
[<simpl_begin (b,e) l; simpl_end (b,e) (List.rev l); simpl_middle (b,e) [] l; simpl_elt (b,e) [] l>]
| _ -> [<>]
and simpl_begin (b,e) = function
| _::Elastic (min,max)::l ->
if min = 0
then [<'Match (false,l,e,"")>]
else [<'Match (false,Elastic (min,min)::l,e,"")>]
| _::l -> [<'Match (false,l,e,"")>]
| [] -> [<>]
and simpl_end (b,e) = function
| _::Elastic (min,max)::l ->
if min = 0
then [<'Match (b,List.rev l,false,"")>]
else [<'Match (b,List.rev (Elastic (min,min)::l),false,"")>]
| _::l -> [<'Match (b,List.rev l,false,"")>]
| [] -> [<>]
and simpl_middle (b,e) acc = function
| [] -> [<>]
| Atom a::l ->
if acc = [ ] then simpl_middle ( b , e ) [ x ] l
else if l = [ ] then [ < > ]
else
else if l = [] then [<>]
else*) [<'Match (b,motif_append acc (motif_cons 1 (Elastic (1,1)) l),e,""); simpl_middle (b,e) (acc@[Atom a]) l>]
| Elastic el::l -> simpl_middle (b,e) (acc@[Elastic el]) l
| Begin::l -> simpl_middle (b,e) [Begin] l
| End::_ -> [<>]
and simpl_elt (b,e) acc = function
| [] -> [<>]
| Atom a::l ->
[<Common.stream_map (fun a' -> Match (b,acc@(Atom a'::l),e,"")) (A.simpl a);
simpl_elt (b,e) (acc@[Atom a]) l>]
| Elastic (min,max)::l ->
if max > min
then [<'Match (b,acc@(if min=0 then l else Elastic (min,min)::l),e,"");
simpl_elt (b,e) (acc@[Elastic (min,max)]) l>]
else simpl_elt (b,e) (acc@[Elastic (min,max)]) l
| Begin::l -> simpl_elt (b,e) [Begin] l
| End::_ -> [<>]
(* logical operations *)
(* top undefined to make 'match []', 'len in ..', and 'dist a in ..' incomparable *)
let rec entails f g =
match f, g with
| Match (_,lf,_,_), Match (_,lg,_,_) -> match_contains lf lg
| Len len1, Len len2 -> Len.entails len1 len2
| Match (true,l,true,_), Len len -> Len.entails (get_length l) len
| Dist _, Dist None -> true
| Dist (Some (a1,d1)), Dist (Some (a2,d2)) -> A.entails a1 a2 & A.entails a2 a1 & Dist.entails d1 d2
| Match (true,l,true,_), Dist None -> true
| Match (true,l,true,_), Dist (Some (a,d)) -> Dist.entails (get_dist a l) d
| _, _ -> false
and match_contains lf lg =
match_begin lf (match lg with [] -> [] | Begin::_ -> lg | _ -> motif_cons 1 (Elastic (0,snd (get_len2 lf))) lg)
and match_begin f g =
match f, g with
| _, [] -> true
| _, [Elastic (0,_)] -> true
| [], _ -> false
| Elastic (min1,max1)::f', Elastic (min2,max2)::g' ->
max1 <= max2 &
let min3, max3 = max 0 (min2-min1), max2-max1 in
min3 <= max3 &
match_begin f' (Elastic (min3, max3)::g')
| Elastic (_,_)::_, _::_ -> false
| Begin::f', Begin::g' ->
match_begin f' g'
| Begin::f', (Atom _ | End)::_ -> false
| End::_, End::_ -> true
| End::_, (Atom _ | Begin)::_ -> false
| Atom a::f', Atom b::g' ->
A.entails a b & match_begin f' g'
| Atom _::_, (Begin | End)::_ -> false
| _::f', Elastic (0,0)::g' ->
match_begin f g'
| Begin::f', Elastic (_,_)::_ ->
match_begin f' g
| End::_, Elastic (0,_)::End::_ -> true
| End::_, Elastic (_,_)::_ -> false
| Atom a::f', Elastic (0,max)::Atom b::g' ->
(A.entails a b & match_begin f' g') or (match_begin f' (Elastic (0, max-1)::Atom b::g'))
| Atom _::f', Elastic (mn,mx)::g' ->
match_begin f' (Elastic (max 0 (mn-1),mx-1)::g')
let conj f g =
if entails f g then f
else if entails g f then g
else raise Not_found
let add f g = conj f g
let sub f g = if entails f g then raise Not_found else f
let rec features = function
| Match (true,l,true,_) ->
(true,Match (false,[],false,"")) ::
(if Param.feat_length then features (Len (get_length l)) else []) @
(if Param.feat_dist
then List.fold_left
(fun res a -> features (Dist (Some (a,get_dist a l))) @ res)
[]
(List.fold_left (fun res -> function Atom a -> LSet.add a res | _ -> res) (LSet.empty ()) l)
else []) @
(if Param.feat_atoms
then
List.fold_left
(fun res -> function
| Atom a -> List.map (fun (vis,x) -> (vis,Match (false,[Atom x],false,""))) (A.features a) @ res
| _ -> res)
[]
l
else [])
| Match m -> []
| Len len -> List.map (fun (vis,x) -> vis,Len x) (Len.features len)
| Dist None -> []
| Dist (Some (a,d)) -> (true,Dist None) :: List.map (fun (vis,x) -> vis,Dist (Some (a,x))) (Dist.features d)
(* operation 'gen' *)
type heur = float
type coord = int * int
type elast = int * int
type link = {e : elast; c : coord}
type cell = {
mutable zs : a LSet.t;
mutable accs : coord LSet.t;
mutable succs : link list;
mutable preds : link list;
mutable heur_right : heur;
mutable heur_left : heur;
mutable heur_end : bool;
}
type mat_dag = {
nf : int;
ng : int;
arfa : a array;
arga : a array;
arfe : elast array;
arge : elast array;
mat : cell array array;
ht_freq : (a, int ref * int ref) Hashtbl.t;
for the nb of z in subsumed by some entry key of the hash table
}
let heur_min =
(* 0. *)
1. (* prob *)
let heur_max h1 h2 =
(* max h1 h2 *)
min h1 h2 (* prob *)
let heur_better h1 h2 =
(* h1 >= h2 *)
h1 <= h2 (* prob *)
let heur_atom md = function
| z::_ ->
- . log ( float ! ( snd ( Hashtbl.find md.ht_freq z ) ) /. float ( md.nf * md.ng ) )
float ( md.nf * md.ng + 1 - ! ( snd ( Hashtbl.find md.ht_freq z ) ) )
sqrt (float !(snd (Hashtbl.find md.ht_freq z)) /. float (md.nf * md.ng)) (* prob *)
| _ -> assert false
let heur_elastic md (min,max) =
let k = 1 . /. float ( md.nf * md.ng ) in
(* float min *. (k +. k) +. (k /. float (max - min + 1)) *)
float ( min+1 ) /. float ( max+1 ) /. float ( max+1 )
( if = 0 then 0 . else -5 . ) - . ( 0.5 * . float ( max - min ) )
float (max - min + 1) (* prob *)
let heur_join md v1 e v2 =
let h = heur_elastic md e in
(* v1 +. h +. v2 *)
v1 *. h *. v2 (* prob *)
let get_link md (i,j) (i',j') =
assert (i<i' & j<j');
let e_i : e ref = let d_i = i' - i - 1 in ref (d_i,d_i) in
for k = i to i'-1 do e_i := e_append !e_i md.arfe.(k) done;
let e_j : e ref = let d_j = j' - j - 1 in ref (d_j,d_j) in
for k = j to j'-1 do e_j := e_append !e_j md.arge.(k) done;
let e = e_union !e_i !e_j in
{e = e; c = (i',j')}
let add_link md (i,j) cell cell' l =
cell.succs <- l::cell.succs;
cell'.preds <- {l with c=(i,j)}::cell'.preds
let get_add_link md (i,j) cell (i',j') cell' =
let l = get_link md (i,j) (i',j') in
add_link md (i,j) cell cell' l;
l
let remove_link md (i,j) cell (i',j') cell' =
cell.succs <- List.filter (fun l -> l.c <> (i',j')) cell.succs;
cell'.preds <- List.filter (fun l -> l.c <> (i,j)) cell'.preds
let gen_match_matdag_succs_cond md (i,j) =
let i1, j1 = i+1, j+1 in
let cell = md.mat.(i).(j) in
let cell_right = md.mat.(i).(j1) in
let cell_down = md.mat.(i1).(j) in
let cell_diag = md.mat.(i1).(j1) in
let my_add_link cell' l =
if Param.gen_floating or cell'.zs = [End] or cell'.succs <> [] (* cell is reachable from end *)
then add_link md (i,j) cell cell' l in
cell.accs <- begin
let accs1 = LSet.union cell_right.accs cell_down.accs in
if LSet.is_empty cell_diag.zs then accs1 else LSet.add (i1,j1) accs1 end;
cell_diag.accs <- []; (* to allow some memory to be freed *)
if not (LSet.is_empty cell.zs)
then begin
let accs_good =
List.iter
(fun (i',j') ->
let cell' = md.mat.(i').(j') in
if ((i,j) = (0,0) & cell'.preds=[])
then my_add_link cell' {e = (0,0); c = (i',j')} (* Warning: e is not significant *)
else
let d = max (i'-i-1) (j'-j-1) in
if Param.gen_link_cond (cell.zs=[Begin]) (d,d) (cell'.zs=[End])
then
let l = get_link md (i,j) (i',j') in
if Param.gen_link_cond (cell.zs=[Begin]) l.e (cell'.zs=[End])
then my_add_link cell' l)
cell.accs in
if not Param.gen_floating & cell.zs <> [End] & cell.succs = [] (* cell is not reachable from end *)
then cell.zs <- LSet.empty () end
let gen_match_matdag lf lg lhs =
let nf = List.fold_left (fun n -> function Elastic _ -> n | _ -> n+1) 0 lf in
let ng = List.fold_left (fun n -> function Elastic _ -> n | _ -> n+1) 0 lg in
let md : mat_dag = {
nf = nf;
ng = ng;
arfa = Array.make (nf+1) Begin;
arga = Array.make (ng+1) Begin;
arfe = Array.make nf (0,0);
arge = Array.make ng (0,0);
mat = Array.make_matrix (nf+2) (ng+2)
{ zs=LSet.empty ();
accs=LSet.empty ();
succs=[]; preds=[];
heur_right=heur_min; heur_left=heur_min; heur_end=true};
ht_freq = Hashtbl.create nf
} in
let cell0 = md.mat.(0).(0) in
(* initializing arfa and arfe *)
ignore (List.fold_left (fun i ->
function
| Elastic e -> md.arfe.(i) <- e; i
| a -> md.arfa.(i+1) <- a; i+1
) 0 lf);
(* initializing arga and arge *)
ignore (List.fold_left (fun j ->
function
| Elastic e -> md.arge.(j) <- e; j
| a -> md.arga.(j+1) <- a; j+1
) 0 lg);
(* computing the fields zs, succs of cells *)
let zhs =
List.fold_left
(fun res lh ->
List.fold_left (fun res' ->
function
| Atom a -> LSet.add a res'
| _ -> res')
res lh)
(LSet.empty ()) lhs in
for s = md.nf + md.ng downto 2 do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s - i in
(* computing zs *)
let zs =
match md.arfa.(i), md.arga.(j) with
| Atom x, Atom y ->
let zhs' =
List.fold_left
(fun res z ->
if A.entails x z & A.entails y z & not (List.exists (fun z' -> A.entails z' z) res)
then LSet.add z (List.filter (fun z' -> not (A.entails z z')) res)
else res)
(LSet.empty ()) zhs in
( match Common.mapfilter
(fun z -> try if not (A.entails (A.top ()) z) then Some (Atom z) else None with Not_found -> Some (Atom z))
(let zs' = A.gen x y zhs' in if zs'=[] then zhs' else zs') with
| [] -> LSet.empty ()
| x::_ -> LSet.singleton x)
| Begin, Begin -> LSet.singleton Begin
| End, End -> LSet.singleton End
| _, _ -> LSet.empty () in
List.iter (fun z ->
try incr (fst (Hashtbl.find md.ht_freq z))
with Not_found -> Hashtbl.add md.ht_freq z (ref 1,ref 0)
) zs;
(* computing succs *)
let cell = {
zs=zs;
accs=LSet.empty ();
succs=[]; preds=[];
heur_right=heur_min; heur_left=heur_min; heur_end=true} in
md.mat.(i).(j) <- cell;
gen_match_matdag_succs_cond md (i,j)
done
done;
(* computing frequencies of each element *)
Hashtbl.iter (fun z (c1,c2) ->
Hashtbl.iter (fun z' (c1',c2') ->
if a_entails z' z then c2 := !c2 + !c1'
) md.ht_freq
) md.ht_freq;
computing succs of cell ( 0,0 ) , taking into account Param.gen_floating
if Param.gen_floating then gen_match_matdag_succs_cond md (0,0)
else if md.nf>0 & md.ng>0 & md.mat.(1).(1).zs=[Begin] then ignore (get_add_link md (0,0) cell0 (1,1) md.mat.(1).(1))
else ();
(* in case Param.gen_floating is false, erase unreachable cells from Begin *)
if not Param.gen_floating then
for s = 2 to md.nf+md.ng do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if cell.preds = [] & cell.zs <> LSet.empty ()
then begin
cell.zs <- LSet.empty ();
List.iter (fun l ->
let cell' = md.mat.(fst l.c).(snd l.c) in
cell'.preds <- List.filter (fun l -> l.c <> (i,j)) cell'.preds
) cell.succs;
cell.succs <- [] end
done
done;
defining the field ' max_heur ' of cells
for s = md.nf+md.ng downto 2 do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if not (LSet.is_empty cell.zs) then
let h = heur_atom md cell.zs in
let hr, he =
List.fold_left
(fun (hr,he) l ->
let hr' = heur_join md h l.e md.mat.(fst l.c).(snd l.c).heur_right in
if heur_better hr' hr or (not Param.gen_floating & he)
then (hr',false)
else (hr,he))
(h,true)
cell.succs in
cell.heur_right <- hr;
cell.heur_end <- he
done
done;
for s = 2 to md.nf+md.ng do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if not (LSet.is_empty cell.zs) then
let h = heur_atom md cell.zs in
let hl, hb =
List.fold_left
(fun (hl,hb) l ->
if l.c = (0,0)
then (hl,false)
else
let hl' = heur_join md h l.e md.mat.(fst l.c).(snd l.c).heur_left in
if heur_better hl' hl or (not Param.gen_floating & hb)
then (hl',false)
else (hl,hb))
(h,true)
cell.preds in
cell.heur_left <- hl;
if Param.gen_floating & hb
then let cell0 = md.mat.(0).(0) in cell0.succs <- {e=(0,0); c=(i,j)}::cell0.succs
(* make this node a possible start for a motif, because every left extension is worse *)
done
done;
(* returning the results *)
md
let gen_insert_motif m (ms, lhs) =
if List.exists (fun lh -> match_contains lh m) lhs
then (ms, lhs)
else (LSet.add m ms, lhs)
let gen_insert_motifs ms' (ms,lhs) =
List.fold_left
(fun res m' -> gen_insert_motif m' res)
(ms,lhs)
ms'
module Sps = Set.Make
(struct
type t = heur * heur * a list * cell
let compare (h1,_,_,_ as x1) (h2,_,_,_ as x2) =
if x1=x2 then 0
else if heur_better h1 h2 then 1
else -1
end)
let rec gen_match_motifs md ps (ms,lhs) =
if List.length ms >= Param.gen_min_xs
then ms
else
if Sps.is_empty ps
then ms
else
let (h,hm,m,cell as x) = Sps.max_elt ps in
let ps' = Sps.remove x ps in
let (ms',lhs') =
if cell.succs = [] or (Param.gen_floating & cell.heur_end)
then begin
gen_insert_motif m (ms,lhs) end
else (ms,lhs) in
let ps'' =
List.fold_left
(fun res l ->
let cell' = md.mat.(fst l.c).(snd l.c) in
let h' = heur_join md hm l.e cell'.heur_right in
let hm' = heur_join md hm l.e (heur_atom md cell'.zs) in
let ma = [List.hd cell'.zs] in
Sps.add (h', hm', m @ (if l.e=(0,0) then [] else [Elastic l.e]) @ ma, cell') res)
ps'
cell.succs in
gen_match_motifs md ps'' (ms',lhs')
let gen_match lf lg lhs =
let md = gen_match_matdag lf lg lhs in
let ps =
List.fold_left
(fun res l ->
let cell = md.mat.(fst l.c).(snd l.c) in
Sps.add (cell.heur_right, heur_atom md cell.zs, [List.hd cell.zs], cell) res)
Sps.empty
md.mat.(0).(0).succs in
gen_match_motifs md ps ([],lhs)
let rec gen f g hs =
match f, g with
| Match (_,[],_,_), Match _
| Match _, Match (_,[],_,_) -> LSet.empty ()
| Match (bf,lf,ef,_), Match (bg,lg,eg,_) ->
let lens =
if bf & ef & bg & eg & Param.gen_len
then gen (Len (get_length lf)) (Len (get_length lg)) hs
else LSet.empty () in
if not (LSet.is_empty lens) then lens else
let lhs = List.fold_left (fun res -> function Match (_,lh,_,_) -> LSet.add lh res | _ -> res) (LSet.empty ()) hs in
let motifs = gen_match lf lg lhs in
List.map
(fun m ->
let b = try List.hd m = Begin with _ -> false in
let e = try List.hd (List.rev m) = End with _ -> false in
Match (b,m,e,""))
motifs
| Match (true,lf,true,_), Len leng ->
gen (Len (get_length lf)) (Len leng) hs
| Len lenf, Match (true,lg,true,_) ->
gen (Len lenf) (Len (get_length lg)) hs
| Len lenf, Len leng ->
let lenhs = Common.mapfilter (function Len len -> Some len | _ -> None) hs in
List.fold_left
(fun res len -> LSet.add (Len len) res)
(LSet.empty ())
(Len.gen lenf leng lenhs)
| _, _ -> LSet.empty ()
end
| null | https://raw.githubusercontent.com/aryx/lfs/b931530c7132b77dfaf3c99d452dc044fce37589/logfun/src/motif.ml | ocaml | * PROSITE-like patterns in sequence, whose elements come from a sub-logic.
* Syntaxtic representation of the 'match' prefix symbol.
* Syntactic representation of the 'begin' symbol.
* Syntactic representation of the 'end' symbol.
* Syntactic representation of the element separator symbol.
* Syntactic representation of the 'any element' symbol.
* Whether to generate motif lengths as features.
* Whether to generate distribution of elements as features.
* Whether to generate atom featues.
* True if 'begin' and 'end' are not compulsory in motifs generated by [gen].
* Whether to allow [gen] to generate features about the lengths.
* Threshold number of generated motifs by [gen].
interval for elastic segments
private functions
public functions
n = parse_repeat;
n = parse_repeat;
logical operations
top undefined to make 'match []', 'len in ..', and 'dist a in ..' incomparable
operation 'gen'
0.
prob
max h1 h2
prob
h1 >= h2
prob
prob
float min *. (k +. k) +. (k /. float (max - min + 1))
prob
v1 +. h +. v2
prob
cell is reachable from end
to allow some memory to be freed
Warning: e is not significant
cell is not reachable from end
initializing arfa and arfe
initializing arga and arge
computing the fields zs, succs of cells
computing zs
computing succs
computing frequencies of each element
in case Param.gen_floating is false, erase unreachable cells from Begin
make this node a possible start for a motif, because every left extension is worse
returning the results |
module type PARAM =
sig
* Condition to be verified on gaps / links in motifs : the 1st/3rd argument respectively tells whether the left / right element is begin / end .
end
module Make (Param : PARAM) (A : Logic.T) =
A.gen must satisfy : A.gen(f , , _ ) = { x } , and A.gen(f , g , A.gen(f , ) ) is empty
struct
include Logic.Default
module IntervParam = struct let verbose = true end
module Len = Openinterval.DotDot(Intpow.Make)
module Dist = Openinterval.DotDot(Floatpow.Make)
type e = int * int
type a = Begin | Atom of A.t | Elastic of e | End
type t = Match of (bool * a list * bool * string)
| Len of Len.t
| Dist of (A.t * Dist.t) option
let print_debug s =
print_endline s;
flush stderr
let a_entails a1 a2 =
match a1, a2 with
| Begin, Begin -> true
| End, End -> true
| Atom x1, Atom x2 -> A.entails x1 x2
| _, _ -> false
let e_contains (min1,max1) (min2,max2) = min1 <= min2 & max2 <= max1
let e_append (min1,max1) (min2,max2) = (min1+min2, max1+max2)
let e_union (min1,max1) (min2,max2) = (min min1 min2, max max1 max2)
let rec get_length l =
let min, max = get_len2 l in
Len.parse (Syntax.of_list
(Token.Ident "in" :: Token.Nat min :: Token.Dot :: Token.Dot :: Token.Nat max :: []))
and get_len2 =
function
| [] -> 0, 0
| Begin::l -> get_len2 l
| End::_ -> 0, 0
| Atom _::l -> let min, max = get_len2 l in min+1, max+1
| Elastic (min,max)::l -> let min', max' = get_len2 l in min+min', max+max'
let rec get_dist a l =
let round x = floor (1000. *. x) /. 1000. in
let (xmin, ymin), (xmax, ymax) = get_dist2 a l in
let dmin = round (float xmin /. float ymin) in
let dmax = round (float xmax /. float ymax) in
Dist.parse (Syntax.of_list (Token.Ident "in" :: Syntax.toks_of_float (dmin,-3) @ Token.Dot :: Token.Dot :: Syntax.toks_of_float (dmax,-3)))
and get_dist2 a =
function
| [] -> (0,0), (0,0)
| Begin::l -> get_dist2 a l
| End::_ -> (0,0), (0,0)
| Atom a'::l ->
let (xmin,ymin), (xmax,ymax) = get_dist2 a l in
if A.entails a' a
then (xmin+1,ymin+1), (xmax+1,ymax+1)
else (xmin,ymin+1), (xmax,ymax+1)
| Elastic (min,max)::l ->
let (xmin,ymin), (xmax,ymax) = get_dist2 a l in
(xmin,ymin+max), (xmax+max,ymax+max)
open Token
let rec motif_cons n x xs =
if n <= 0
then xs
else motif_cons (n-1) x
( match x, xs with
| Begin, Begin::_ -> xs
| Begin, _ -> Begin::xs
| End, _ -> [End]
| Atom a, _ -> Atom a::xs
| Elastic (min,max), Elastic (min',max')::xs' -> Elastic (min+min',max+max')::xs'
| Elastic e, _ -> Elastic e::xs)
let motif_append m1 m2 =
List.fold_right (motif_cons 1) m1 m2
let print_e = function
| ( 0,1 ) - > [ ]
| (0,1) -> [Interro]
*)
| (1,1) -> []
| (min,max) ->
if max = min
then [LeftPar; Nat min; RightPar]
else [LeftPar; Nat min; Comma; Nat max; RightPar]
let rec print_seq = function
| l -> print_seq_loop true l
and print_seq_loop first_atom = function
| [] -> []
| Begin::l -> Param.toks_begin @ print_seq_loop true l
| End::l -> Param.toks_end @ print_seq_loop true l
| x::l -> print_seq_sep first_atom @ print_atom x @ print_seq_loop false l
and print_seq_sep first_atom =
if first_atom
then []
else Param.toks_sep
and print_atom = function
| Atom a -> A.print a
| Elastic e -> Param.toks_any @ print_e e
| _ -> assert false
let print_comment = function
| "" -> []
| c -> [Colon; String c]
let print = function
| Match (_,l,_, c) -> Param.toks_match @ print_seq l @ print_comment c
| Len length -> Ident "length" :: PP_tilda :: Len.print length
| Dist None -> [Ident "dist"]
| Dist (Some (a,d)) -> Ident "dist" :: PP_tilda :: A.print a @ PP_tilda :: Dist.print d
let parse_repeat = parser
| [<'LeftPar; 'Nat n; 'RightPar>] -> n
| [<>] -> 1
let parse_e = parser
| [<'LeftPar;
'Nat min ?? "Syntax error: positive integer expected in motif gap, after '('";
str
>] ->
( match str with parser
| [<'RightPar>] -> (min,min)
| [<'Comma;
'Nat max when max >= min ?? "Syntax error: integer expected in motif gap, after: " ^ Syntax.stringizer [LeftPar; Nat min; Comma];
'RightPar ?? "Syntax error: missing ')' in motif gap, after: " ^ Syntax.stringizer [LeftPar; Nat min; Comma; Nat max]
>] -> (min,max)
| [<>] -> raise (Stream.Error ("Syntax error: ')' or ',' expected after: " ^ Syntax.stringizer [LeftPar; Nat min]))
)
| [<>] -> (1,1)
| [ < ' > ] - > ( 0,1 )
| [<'Interro>] -> (0,1)
*)
let rec parse_seq = parser
| [<_ = Syntax.parse_tokens Param.toks_begin;
l, e = parse_seq_loop1 ?? "Syntax error: motif element, gap or end expected after: " ^ Syntax.stringizer Param.toks_begin
>] -> true, motif_cons 1 Begin l, e
| [<l, e = parse_seq_loop1>] -> false, l, e
| [<>] -> false, [], false
and parse_seq_loop1 = parser
| [<_ = Syntax.parse_tokens Param.toks_end>] ->
[End], true
| [<_ = Syntax.parse_tokens Param.toks_any;
elast = parse_e;
l, e = parse_seq_loop2
>] ->
motif_cons 1 (Elastic elast) l, e
l, e = parse_seq_loop2
>] ->
motif_cons 1 a l, e
| [<>] -> [], false
and parse_seq_loop2 = parser
| [<_ = Syntax.parse_tokens Param.toks_end>] -> [End], true
| [<_ = Syntax.parse_tokens Param.toks_sep;
l, e = parse_seq_loop1 ?? "Syntax error: motif element, gap or end expected after: " ^ Syntax.stringizer Param.toks_sep
>] -> l, e
| [<>] -> [], false
and parse_seq_is = parser
l = parse_seq_is ?? "Syntax error: motif element expected after: " ^ Syntax.stringizer (A.print a)
>] -> motif_cons 1 x l
| [<>] -> [End]
and parse_atom = parser
| [<a = A.parse>] ->
if try A.entails (A.top ()) a with Not_found -> false
then Elastic (1,1), a
else Atom a, a
let parse_comment = parser
| [<'Colon; 'String c>] -> c
| [<>] -> ""
let parse = parser
| [<'Ident l when l.[0] = 'l';
length = Len.parse ?? "Syntax error in motif after '" ^ l ^ "'"
>] -> Len length
| [<'Ident d when d.[0] = 'd'; str>] -> (match str with parser
| [<a = A.parse;
d = Dist.parse ?? "Syntax error in motif after: " ^ Syntax.stringizer (Ident d :: A.print a)
>] -> Dist (Some (a,d))
| [<>] -> Dist None)
| [<'Ident "is";
toks = A.parse_compact ?? "Syntax error after 'is'";
c = parse_comment
>] -> Match (true, Begin::parse_seq_is (Syntax.of_list toks), true, c)
| [<b, l, e = Syntax.parse_tokens_and Param.toks_match parse_seq;
c = parse_comment
>] -> Match (b,l,e,c)
let rec simpl = function
| Match (b,l,e, c) ->
[<simpl_begin (b,e) l; simpl_end (b,e) (List.rev l); simpl_middle (b,e) [] l; simpl_elt (b,e) [] l>]
| _ -> [<>]
and simpl_begin (b,e) = function
| _::Elastic (min,max)::l ->
if min = 0
then [<'Match (false,l,e,"")>]
else [<'Match (false,Elastic (min,min)::l,e,"")>]
| _::l -> [<'Match (false,l,e,"")>]
| [] -> [<>]
and simpl_end (b,e) = function
| _::Elastic (min,max)::l ->
if min = 0
then [<'Match (b,List.rev l,false,"")>]
else [<'Match (b,List.rev (Elastic (min,min)::l),false,"")>]
| _::l -> [<'Match (b,List.rev l,false,"")>]
| [] -> [<>]
and simpl_middle (b,e) acc = function
| [] -> [<>]
| Atom a::l ->
if acc = [ ] then simpl_middle ( b , e ) [ x ] l
else if l = [ ] then [ < > ]
else
else if l = [] then [<>]
else*) [<'Match (b,motif_append acc (motif_cons 1 (Elastic (1,1)) l),e,""); simpl_middle (b,e) (acc@[Atom a]) l>]
| Elastic el::l -> simpl_middle (b,e) (acc@[Elastic el]) l
| Begin::l -> simpl_middle (b,e) [Begin] l
| End::_ -> [<>]
and simpl_elt (b,e) acc = function
| [] -> [<>]
| Atom a::l ->
[<Common.stream_map (fun a' -> Match (b,acc@(Atom a'::l),e,"")) (A.simpl a);
simpl_elt (b,e) (acc@[Atom a]) l>]
| Elastic (min,max)::l ->
if max > min
then [<'Match (b,acc@(if min=0 then l else Elastic (min,min)::l),e,"");
simpl_elt (b,e) (acc@[Elastic (min,max)]) l>]
else simpl_elt (b,e) (acc@[Elastic (min,max)]) l
| Begin::l -> simpl_elt (b,e) [Begin] l
| End::_ -> [<>]
let rec entails f g =
match f, g with
| Match (_,lf,_,_), Match (_,lg,_,_) -> match_contains lf lg
| Len len1, Len len2 -> Len.entails len1 len2
| Match (true,l,true,_), Len len -> Len.entails (get_length l) len
| Dist _, Dist None -> true
| Dist (Some (a1,d1)), Dist (Some (a2,d2)) -> A.entails a1 a2 & A.entails a2 a1 & Dist.entails d1 d2
| Match (true,l,true,_), Dist None -> true
| Match (true,l,true,_), Dist (Some (a,d)) -> Dist.entails (get_dist a l) d
| _, _ -> false
and match_contains lf lg =
match_begin lf (match lg with [] -> [] | Begin::_ -> lg | _ -> motif_cons 1 (Elastic (0,snd (get_len2 lf))) lg)
and match_begin f g =
match f, g with
| _, [] -> true
| _, [Elastic (0,_)] -> true
| [], _ -> false
| Elastic (min1,max1)::f', Elastic (min2,max2)::g' ->
max1 <= max2 &
let min3, max3 = max 0 (min2-min1), max2-max1 in
min3 <= max3 &
match_begin f' (Elastic (min3, max3)::g')
| Elastic (_,_)::_, _::_ -> false
| Begin::f', Begin::g' ->
match_begin f' g'
| Begin::f', (Atom _ | End)::_ -> false
| End::_, End::_ -> true
| End::_, (Atom _ | Begin)::_ -> false
| Atom a::f', Atom b::g' ->
A.entails a b & match_begin f' g'
| Atom _::_, (Begin | End)::_ -> false
| _::f', Elastic (0,0)::g' ->
match_begin f g'
| Begin::f', Elastic (_,_)::_ ->
match_begin f' g
| End::_, Elastic (0,_)::End::_ -> true
| End::_, Elastic (_,_)::_ -> false
| Atom a::f', Elastic (0,max)::Atom b::g' ->
(A.entails a b & match_begin f' g') or (match_begin f' (Elastic (0, max-1)::Atom b::g'))
| Atom _::f', Elastic (mn,mx)::g' ->
match_begin f' (Elastic (max 0 (mn-1),mx-1)::g')
let conj f g =
if entails f g then f
else if entails g f then g
else raise Not_found
let add f g = conj f g
let sub f g = if entails f g then raise Not_found else f
let rec features = function
| Match (true,l,true,_) ->
(true,Match (false,[],false,"")) ::
(if Param.feat_length then features (Len (get_length l)) else []) @
(if Param.feat_dist
then List.fold_left
(fun res a -> features (Dist (Some (a,get_dist a l))) @ res)
[]
(List.fold_left (fun res -> function Atom a -> LSet.add a res | _ -> res) (LSet.empty ()) l)
else []) @
(if Param.feat_atoms
then
List.fold_left
(fun res -> function
| Atom a -> List.map (fun (vis,x) -> (vis,Match (false,[Atom x],false,""))) (A.features a) @ res
| _ -> res)
[]
l
else [])
| Match m -> []
| Len len -> List.map (fun (vis,x) -> vis,Len x) (Len.features len)
| Dist None -> []
| Dist (Some (a,d)) -> (true,Dist None) :: List.map (fun (vis,x) -> vis,Dist (Some (a,x))) (Dist.features d)
type heur = float
type coord = int * int
type elast = int * int
type link = {e : elast; c : coord}
type cell = {
mutable zs : a LSet.t;
mutable accs : coord LSet.t;
mutable succs : link list;
mutable preds : link list;
mutable heur_right : heur;
mutable heur_left : heur;
mutable heur_end : bool;
}
type mat_dag = {
nf : int;
ng : int;
arfa : a array;
arga : a array;
arfe : elast array;
arge : elast array;
mat : cell array array;
ht_freq : (a, int ref * int ref) Hashtbl.t;
for the nb of z in subsumed by some entry key of the hash table
}
let heur_min =
let heur_max h1 h2 =
let heur_better h1 h2 =
let heur_atom md = function
| z::_ ->
- . log ( float ! ( snd ( Hashtbl.find md.ht_freq z ) ) /. float ( md.nf * md.ng ) )
float ( md.nf * md.ng + 1 - ! ( snd ( Hashtbl.find md.ht_freq z ) ) )
| _ -> assert false
let heur_elastic md (min,max) =
let k = 1 . /. float ( md.nf * md.ng ) in
float ( min+1 ) /. float ( max+1 ) /. float ( max+1 )
( if = 0 then 0 . else -5 . ) - . ( 0.5 * . float ( max - min ) )
let heur_join md v1 e v2 =
let h = heur_elastic md e in
let get_link md (i,j) (i',j') =
assert (i<i' & j<j');
let e_i : e ref = let d_i = i' - i - 1 in ref (d_i,d_i) in
for k = i to i'-1 do e_i := e_append !e_i md.arfe.(k) done;
let e_j : e ref = let d_j = j' - j - 1 in ref (d_j,d_j) in
for k = j to j'-1 do e_j := e_append !e_j md.arge.(k) done;
let e = e_union !e_i !e_j in
{e = e; c = (i',j')}
let add_link md (i,j) cell cell' l =
cell.succs <- l::cell.succs;
cell'.preds <- {l with c=(i,j)}::cell'.preds
let get_add_link md (i,j) cell (i',j') cell' =
let l = get_link md (i,j) (i',j') in
add_link md (i,j) cell cell' l;
l
let remove_link md (i,j) cell (i',j') cell' =
cell.succs <- List.filter (fun l -> l.c <> (i',j')) cell.succs;
cell'.preds <- List.filter (fun l -> l.c <> (i,j)) cell'.preds
let gen_match_matdag_succs_cond md (i,j) =
let i1, j1 = i+1, j+1 in
let cell = md.mat.(i).(j) in
let cell_right = md.mat.(i).(j1) in
let cell_down = md.mat.(i1).(j) in
let cell_diag = md.mat.(i1).(j1) in
let my_add_link cell' l =
then add_link md (i,j) cell cell' l in
cell.accs <- begin
let accs1 = LSet.union cell_right.accs cell_down.accs in
if LSet.is_empty cell_diag.zs then accs1 else LSet.add (i1,j1) accs1 end;
if not (LSet.is_empty cell.zs)
then begin
let accs_good =
List.iter
(fun (i',j') ->
let cell' = md.mat.(i').(j') in
if ((i,j) = (0,0) & cell'.preds=[])
else
let d = max (i'-i-1) (j'-j-1) in
if Param.gen_link_cond (cell.zs=[Begin]) (d,d) (cell'.zs=[End])
then
let l = get_link md (i,j) (i',j') in
if Param.gen_link_cond (cell.zs=[Begin]) l.e (cell'.zs=[End])
then my_add_link cell' l)
cell.accs in
then cell.zs <- LSet.empty () end
let gen_match_matdag lf lg lhs =
let nf = List.fold_left (fun n -> function Elastic _ -> n | _ -> n+1) 0 lf in
let ng = List.fold_left (fun n -> function Elastic _ -> n | _ -> n+1) 0 lg in
let md : mat_dag = {
nf = nf;
ng = ng;
arfa = Array.make (nf+1) Begin;
arga = Array.make (ng+1) Begin;
arfe = Array.make nf (0,0);
arge = Array.make ng (0,0);
mat = Array.make_matrix (nf+2) (ng+2)
{ zs=LSet.empty ();
accs=LSet.empty ();
succs=[]; preds=[];
heur_right=heur_min; heur_left=heur_min; heur_end=true};
ht_freq = Hashtbl.create nf
} in
let cell0 = md.mat.(0).(0) in
ignore (List.fold_left (fun i ->
function
| Elastic e -> md.arfe.(i) <- e; i
| a -> md.arfa.(i+1) <- a; i+1
) 0 lf);
ignore (List.fold_left (fun j ->
function
| Elastic e -> md.arge.(j) <- e; j
| a -> md.arga.(j+1) <- a; j+1
) 0 lg);
let zhs =
List.fold_left
(fun res lh ->
List.fold_left (fun res' ->
function
| Atom a -> LSet.add a res'
| _ -> res')
res lh)
(LSet.empty ()) lhs in
for s = md.nf + md.ng downto 2 do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s - i in
let zs =
match md.arfa.(i), md.arga.(j) with
| Atom x, Atom y ->
let zhs' =
List.fold_left
(fun res z ->
if A.entails x z & A.entails y z & not (List.exists (fun z' -> A.entails z' z) res)
then LSet.add z (List.filter (fun z' -> not (A.entails z z')) res)
else res)
(LSet.empty ()) zhs in
( match Common.mapfilter
(fun z -> try if not (A.entails (A.top ()) z) then Some (Atom z) else None with Not_found -> Some (Atom z))
(let zs' = A.gen x y zhs' in if zs'=[] then zhs' else zs') with
| [] -> LSet.empty ()
| x::_ -> LSet.singleton x)
| Begin, Begin -> LSet.singleton Begin
| End, End -> LSet.singleton End
| _, _ -> LSet.empty () in
List.iter (fun z ->
try incr (fst (Hashtbl.find md.ht_freq z))
with Not_found -> Hashtbl.add md.ht_freq z (ref 1,ref 0)
) zs;
let cell = {
zs=zs;
accs=LSet.empty ();
succs=[]; preds=[];
heur_right=heur_min; heur_left=heur_min; heur_end=true} in
md.mat.(i).(j) <- cell;
gen_match_matdag_succs_cond md (i,j)
done
done;
Hashtbl.iter (fun z (c1,c2) ->
Hashtbl.iter (fun z' (c1',c2') ->
if a_entails z' z then c2 := !c2 + !c1'
) md.ht_freq
) md.ht_freq;
computing succs of cell ( 0,0 ) , taking into account Param.gen_floating
if Param.gen_floating then gen_match_matdag_succs_cond md (0,0)
else if md.nf>0 & md.ng>0 & md.mat.(1).(1).zs=[Begin] then ignore (get_add_link md (0,0) cell0 (1,1) md.mat.(1).(1))
else ();
if not Param.gen_floating then
for s = 2 to md.nf+md.ng do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if cell.preds = [] & cell.zs <> LSet.empty ()
then begin
cell.zs <- LSet.empty ();
List.iter (fun l ->
let cell' = md.mat.(fst l.c).(snd l.c) in
cell'.preds <- List.filter (fun l -> l.c <> (i,j)) cell'.preds
) cell.succs;
cell.succs <- [] end
done
done;
defining the field ' max_heur ' of cells
for s = md.nf+md.ng downto 2 do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if not (LSet.is_empty cell.zs) then
let h = heur_atom md cell.zs in
let hr, he =
List.fold_left
(fun (hr,he) l ->
let hr' = heur_join md h l.e md.mat.(fst l.c).(snd l.c).heur_right in
if heur_better hr' hr or (not Param.gen_floating & he)
then (hr',false)
else (hr,he))
(h,true)
cell.succs in
cell.heur_right <- hr;
cell.heur_end <- he
done
done;
for s = 2 to md.nf+md.ng do
for i = max 1 (s-md.ng) to min md.nf (s-1) do
let j = s-i in
let cell = md.mat.(i).(j) in
if not (LSet.is_empty cell.zs) then
let h = heur_atom md cell.zs in
let hl, hb =
List.fold_left
(fun (hl,hb) l ->
if l.c = (0,0)
then (hl,false)
else
let hl' = heur_join md h l.e md.mat.(fst l.c).(snd l.c).heur_left in
if heur_better hl' hl or (not Param.gen_floating & hb)
then (hl',false)
else (hl,hb))
(h,true)
cell.preds in
cell.heur_left <- hl;
if Param.gen_floating & hb
then let cell0 = md.mat.(0).(0) in cell0.succs <- {e=(0,0); c=(i,j)}::cell0.succs
done
done;
md
let gen_insert_motif m (ms, lhs) =
if List.exists (fun lh -> match_contains lh m) lhs
then (ms, lhs)
else (LSet.add m ms, lhs)
let gen_insert_motifs ms' (ms,lhs) =
List.fold_left
(fun res m' -> gen_insert_motif m' res)
(ms,lhs)
ms'
module Sps = Set.Make
(struct
type t = heur * heur * a list * cell
let compare (h1,_,_,_ as x1) (h2,_,_,_ as x2) =
if x1=x2 then 0
else if heur_better h1 h2 then 1
else -1
end)
let rec gen_match_motifs md ps (ms,lhs) =
if List.length ms >= Param.gen_min_xs
then ms
else
if Sps.is_empty ps
then ms
else
let (h,hm,m,cell as x) = Sps.max_elt ps in
let ps' = Sps.remove x ps in
let (ms',lhs') =
if cell.succs = [] or (Param.gen_floating & cell.heur_end)
then begin
gen_insert_motif m (ms,lhs) end
else (ms,lhs) in
let ps'' =
List.fold_left
(fun res l ->
let cell' = md.mat.(fst l.c).(snd l.c) in
let h' = heur_join md hm l.e cell'.heur_right in
let hm' = heur_join md hm l.e (heur_atom md cell'.zs) in
let ma = [List.hd cell'.zs] in
Sps.add (h', hm', m @ (if l.e=(0,0) then [] else [Elastic l.e]) @ ma, cell') res)
ps'
cell.succs in
gen_match_motifs md ps'' (ms',lhs')
let gen_match lf lg lhs =
let md = gen_match_matdag lf lg lhs in
let ps =
List.fold_left
(fun res l ->
let cell = md.mat.(fst l.c).(snd l.c) in
Sps.add (cell.heur_right, heur_atom md cell.zs, [List.hd cell.zs], cell) res)
Sps.empty
md.mat.(0).(0).succs in
gen_match_motifs md ps ([],lhs)
let rec gen f g hs =
match f, g with
| Match (_,[],_,_), Match _
| Match _, Match (_,[],_,_) -> LSet.empty ()
| Match (bf,lf,ef,_), Match (bg,lg,eg,_) ->
let lens =
if bf & ef & bg & eg & Param.gen_len
then gen (Len (get_length lf)) (Len (get_length lg)) hs
else LSet.empty () in
if not (LSet.is_empty lens) then lens else
let lhs = List.fold_left (fun res -> function Match (_,lh,_,_) -> LSet.add lh res | _ -> res) (LSet.empty ()) hs in
let motifs = gen_match lf lg lhs in
List.map
(fun m ->
let b = try List.hd m = Begin with _ -> false in
let e = try List.hd (List.rev m) = End with _ -> false in
Match (b,m,e,""))
motifs
| Match (true,lf,true,_), Len leng ->
gen (Len (get_length lf)) (Len leng) hs
| Len lenf, Match (true,lg,true,_) ->
gen (Len lenf) (Len (get_length lg)) hs
| Len lenf, Len leng ->
let lenhs = Common.mapfilter (function Len len -> Some len | _ -> None) hs in
List.fold_left
(fun res len -> LSet.add (Len len) res)
(LSet.empty ())
(Len.gen lenf leng lenhs)
| _, _ -> LSet.empty ()
end
|
d5e738999c4383d829912b7a3d4e0652d3b266841f0c1ec692b0dc3166df2e05 | keyvanakbary/marko | components.cljs | (ns marko.components
(:require
[reagent.core :as r]
["easymde" :as easymde]))
(def id-counter (atom 0))
(defn- generate-id []
(swap! id-counter inc)
(str "editor-" @id-counter))
(defn editor [{:keys [id value options on-change]
:or {id (generate-id)}}]
(let [!key-change (atom false)
!editor (atom nil)
!value (atom value)
trigger-change (fn []
(let [editor-value (.value @!editor)]
(reset! !key-change true)
(reset! !value editor-value)
(if on-change
(on-change editor-value))))]
(r/create-class
{:display-name "editor"
:component-did-mount
(fn [this]
(let [all-options
(-> options
(merge {:element (js/document.getElementById id)
:initialValue (:value (r/props this))})
(clj->js))]
(reset! !editor (easymde. all-options))))
:component-did-update
(fn [this [_ {old-value :value}]]
(let [props-value (:value (r/props this))]
(if (or (and (not @!key-change)
(not= props-value old-value))
(not= props-value @!value))
(.value @!editor props-value))
(reset! !key-change false)))
:reagent-render
(fn []
[:div
{:id (str id "-wrapper")
:on-key-up trigger-change
:on-paste trigger-change}
[:textarea {:id id}]])}))) | null | https://raw.githubusercontent.com/keyvanakbary/marko/392602803795d7a5ab4dc8242c1625aca9b0cc20/src/marko/components.cljs | clojure | (ns marko.components
(:require
[reagent.core :as r]
["easymde" :as easymde]))
(def id-counter (atom 0))
(defn- generate-id []
(swap! id-counter inc)
(str "editor-" @id-counter))
(defn editor [{:keys [id value options on-change]
:or {id (generate-id)}}]
(let [!key-change (atom false)
!editor (atom nil)
!value (atom value)
trigger-change (fn []
(let [editor-value (.value @!editor)]
(reset! !key-change true)
(reset! !value editor-value)
(if on-change
(on-change editor-value))))]
(r/create-class
{:display-name "editor"
:component-did-mount
(fn [this]
(let [all-options
(-> options
(merge {:element (js/document.getElementById id)
:initialValue (:value (r/props this))})
(clj->js))]
(reset! !editor (easymde. all-options))))
:component-did-update
(fn [this [_ {old-value :value}]]
(let [props-value (:value (r/props this))]
(if (or (and (not @!key-change)
(not= props-value old-value))
(not= props-value @!value))
(.value @!editor props-value))
(reset! !key-change false)))
:reagent-render
(fn []
[:div
{:id (str id "-wrapper")
:on-key-up trigger-change
:on-paste trigger-change}
[:textarea {:id id}]])}))) | |
bb94805958e06daeb6dc64580bb37e8f14b16cf0f06350df9276f2c2ce00802b | protolude/protolude | List.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE Safe #-}
module Protolude.List
( head,
ordNub,
sortOn,
list,
product,
sum,
groupBy,
)
where
import Control.Applicative (pure)
import Data.Foldable (Foldable, foldl', foldr)
import Data.Function ((.))
import Data.Functor (fmap)
import Data.List (groupBy, sortBy)
import Data.Maybe (Maybe (Nothing))
import Data.Ord (Ord, comparing)
import qualified Data.Set as Set
import GHC.Num ((*), (+), Num)
head :: (Foldable f) => f a -> Maybe a
head = foldr (\x _ -> pure x) Nothing
sortOn :: (Ord o) => (a -> o) -> [a] -> [a]
sortOn = sortBy . comparing
-- O(n * log n)
ordNub :: (Ord a) => [a] -> [a]
ordNub l = go Set.empty l
where
go _ [] = []
go s (x : xs) =
if x `Set.member` s
then go s xs
else x : go (Set.insert x s) xs
list :: [b] -> (a -> b) -> [a] -> [b]
list def f xs = case xs of
[] -> def
_ -> fmap f xs
# INLINE product #
product :: (Foldable f, Num a) => f a -> a
product = foldl' (*) 1
# INLINE sum #
sum :: (Foldable f, Num a) => f a -> a
sum = foldl' (+) 0
| null | https://raw.githubusercontent.com/protolude/protolude/e613ed4dd20b7b860fca326e11269af2104a196e/src/Protolude/List.hs | haskell | # LANGUAGE Safe #
O(n * log n) | # LANGUAGE NoImplicitPrelude #
module Protolude.List
( head,
ordNub,
sortOn,
list,
product,
sum,
groupBy,
)
where
import Control.Applicative (pure)
import Data.Foldable (Foldable, foldl', foldr)
import Data.Function ((.))
import Data.Functor (fmap)
import Data.List (groupBy, sortBy)
import Data.Maybe (Maybe (Nothing))
import Data.Ord (Ord, comparing)
import qualified Data.Set as Set
import GHC.Num ((*), (+), Num)
head :: (Foldable f) => f a -> Maybe a
head = foldr (\x _ -> pure x) Nothing
sortOn :: (Ord o) => (a -> o) -> [a] -> [a]
sortOn = sortBy . comparing
ordNub :: (Ord a) => [a] -> [a]
ordNub l = go Set.empty l
where
go _ [] = []
go s (x : xs) =
if x `Set.member` s
then go s xs
else x : go (Set.insert x s) xs
list :: [b] -> (a -> b) -> [a] -> [b]
list def f xs = case xs of
[] -> def
_ -> fmap f xs
# INLINE product #
product :: (Foldable f, Num a) => f a -> a
product = foldl' (*) 1
# INLINE sum #
sum :: (Foldable f, Num a) => f a -> a
sum = foldl' (+) 0
|
d4e6a712b8ca539a774ddcd6909e90f9f1a8a26fe79ebce71cd8df27b25272af | solita/laundry | xlsx_test.clj | (ns laundry.xlsx-test
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[laundry.test.fixture :as fixture]
[peridot.multipart]
[ring.mock.request :as mock]
[ring.util.request]))
(deftest ^:integration api-xlsx
(let [app (fixture/get-app)
file (io/file (io/resource "test.xls"))
_ (assert file)
request (-> (mock/request :post "/xlsx/xlsx2pdf")
(merge (peridot.multipart/build {:file file})))
response (app request)
body (ring.util.request/body-string response)]
(is (= 200 (:status response)))
(is (clojure.string/starts-with? body "%PDF-1.4"))))
| null | https://raw.githubusercontent.com/solita/laundry/4e1fe96ebae19cde14c3ba5396929ba1578b7715/test/laundry/xlsx_test.clj | clojure | (ns laundry.xlsx-test
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[laundry.test.fixture :as fixture]
[peridot.multipart]
[ring.mock.request :as mock]
[ring.util.request]))
(deftest ^:integration api-xlsx
(let [app (fixture/get-app)
file (io/file (io/resource "test.xls"))
_ (assert file)
request (-> (mock/request :post "/xlsx/xlsx2pdf")
(merge (peridot.multipart/build {:file file})))
response (app request)
body (ring.util.request/body-string response)]
(is (= 200 (:status response)))
(is (clojure.string/starts-with? body "%PDF-1.4"))))
| |
14f452e1d808605c3b7d75569b42b1cf92774afad129d1ffe0146e9c239559cc | hexlet-basics/exercises-clojure | test.clj | (ns about-state-test
(:require [test-helper :refer [assert-solution]]
[index :refer [transit]]))
(assert-solution
[[(atom 100) (atom 50) 20] [(atom 10) (atom 100) 10] [(atom 50) (atom 30) 50]]
[[80 70] [0 110] [0 80]]
transit)
| null | https://raw.githubusercontent.com/hexlet-basics/exercises-clojure/ede14102d01f9ef736e0af811cd92f5b22a83bc2/modules/45-state/10-about-state/test.clj | clojure | (ns about-state-test
(:require [test-helper :refer [assert-solution]]
[index :refer [transit]]))
(assert-solution
[[(atom 100) (atom 50) 20] [(atom 10) (atom 100) 10] [(atom 50) (atom 30) 50]]
[[80 70] [0 110] [0 80]]
transit)
| |
3548df7817bef0ace2f01c83c3a2742f91664307821ec50b5d74f0632b60483e | bfontaine/grape | models_test.clj | (ns grape.impl.models-test
(:require [clojure.test :refer :all]
[grape.impl.models :as m]
[grape.impl.parsing :as p]))
(deftest tree-node?-test
(are [x] (m/tree-node? x)
(list :keyword "foo")
(list :list (list :keyword "x") (list :symbol "y"))
(list :whitespace " "))
(are [x] (not (m/tree-node? x))
"terminal"))
(deftest tree-leave?-test
(is (m/tree-leave? " "))
(is (not (m/tree-leave? (list :keyword "abc")))))
(deftest pattern?-test
(are [x] (m/pattern? x)
(list :symbol "$")
(list :keyword "a")
(list :vector)))
(deftest node-type-test
(is (= :foo (m/node-type (list :foo "terminal")))))
(deftest node-children-test
(let [children (map #(list :keyword %) ["a" "b" "c"])]
(is (= children
(m/node-children (cons :vector children))))))
(deftest node-child-test
(let [s (list :symbol "foo")]
(is (= s (m/node-child (list :vector s))))))
(deftest wildcard?-test
(are [expected node]
(= expected (boolean (m/wildcard? node)))
false (list :keyword "$foo")
false (list :symbol "foo")
true (list :symbol "$foo")
true (list :symbol "$list&")))
(deftest multi-wildcard?-test
(are [expected node]
(= expected (boolean (m/multi-wildcard? node)))
false (list :keyword "$foo")
false (list :symbol "$foo")
true (list :symbol "$foo&")))
(deftest node-wildcard-test
(are [expected s]
(= expected (m/node-wildcard (list :symbol s)))
nil "$nope"
nil "$nope&"
{:node-type :_all :multiple? false} "$"
{:node-type :keyword :multiple? false} "$keyword"
{:node-type :macro_keyword :multiple? false} "$macro-keyword"
{:node-type :_all :multiple? true} "$&"
{:node-type :keyword :multiple? true} "$keyword&"))
(deftest compact-whitespaces-test
(testing "leading/trailing whitespaces"
(let [compact '(:code (:vector (:symbol "a") (:whitespace " ") (:symbol "b")))]
(are [original]
(= compact (m/compact-whitespaces original))
compact
'(:code (:vector (:symbol "a") (:whitespace " ") (:symbol "b") (:whitespace " ")))
'(:code (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b")))
'(:code (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b") (:whitespace " ")))
'(:code (:whitespace " ") (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b"))))))
(testing "whitespaces in strings"
(let [code '(:code (:string " a \n "))]
(is (= code (m/compact-whitespaces code)))))
(testing "parse/unparse tests"
(are [expected code]
(= expected (p/unparse-code (m/compact-whitespaces (p/parse-code code))))
"foo" " foo "
"hey" "hey\n"
"various" " various\r\t \n"
"[a b c]" "[a b c] "
"#_foo bar" "#_ foo\nbar"
"[a b]" "[a b ]"
"a b c" "a b c"
"[a b]" "[a, ,,b]"))) | null | https://raw.githubusercontent.com/bfontaine/grape/51d741943595f55fd51c34b0213037ca484a1bfb/test/grape/impl/models_test.clj | clojure | (ns grape.impl.models-test
(:require [clojure.test :refer :all]
[grape.impl.models :as m]
[grape.impl.parsing :as p]))
(deftest tree-node?-test
(are [x] (m/tree-node? x)
(list :keyword "foo")
(list :list (list :keyword "x") (list :symbol "y"))
(list :whitespace " "))
(are [x] (not (m/tree-node? x))
"terminal"))
(deftest tree-leave?-test
(is (m/tree-leave? " "))
(is (not (m/tree-leave? (list :keyword "abc")))))
(deftest pattern?-test
(are [x] (m/pattern? x)
(list :symbol "$")
(list :keyword "a")
(list :vector)))
(deftest node-type-test
(is (= :foo (m/node-type (list :foo "terminal")))))
(deftest node-children-test
(let [children (map #(list :keyword %) ["a" "b" "c"])]
(is (= children
(m/node-children (cons :vector children))))))
(deftest node-child-test
(let [s (list :symbol "foo")]
(is (= s (m/node-child (list :vector s))))))
(deftest wildcard?-test
(are [expected node]
(= expected (boolean (m/wildcard? node)))
false (list :keyword "$foo")
false (list :symbol "foo")
true (list :symbol "$foo")
true (list :symbol "$list&")))
(deftest multi-wildcard?-test
(are [expected node]
(= expected (boolean (m/multi-wildcard? node)))
false (list :keyword "$foo")
false (list :symbol "$foo")
true (list :symbol "$foo&")))
(deftest node-wildcard-test
(are [expected s]
(= expected (m/node-wildcard (list :symbol s)))
nil "$nope"
nil "$nope&"
{:node-type :_all :multiple? false} "$"
{:node-type :keyword :multiple? false} "$keyword"
{:node-type :macro_keyword :multiple? false} "$macro-keyword"
{:node-type :_all :multiple? true} "$&"
{:node-type :keyword :multiple? true} "$keyword&"))
(deftest compact-whitespaces-test
(testing "leading/trailing whitespaces"
(let [compact '(:code (:vector (:symbol "a") (:whitespace " ") (:symbol "b")))]
(are [original]
(= compact (m/compact-whitespaces original))
compact
'(:code (:vector (:symbol "a") (:whitespace " ") (:symbol "b") (:whitespace " ")))
'(:code (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b")))
'(:code (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b") (:whitespace " ")))
'(:code (:whitespace " ") (:vector (:whitespace " ") (:symbol "a") (:whitespace " ") (:symbol "b"))))))
(testing "whitespaces in strings"
(let [code '(:code (:string " a \n "))]
(is (= code (m/compact-whitespaces code)))))
(testing "parse/unparse tests"
(are [expected code]
(= expected (p/unparse-code (m/compact-whitespaces (p/parse-code code))))
"foo" " foo "
"hey" "hey\n"
"various" " various\r\t \n"
"[a b c]" "[a b c] "
"#_foo bar" "#_ foo\nbar"
"[a b]" "[a b ]"
"a b c" "a b c"
"[a b]" "[a, ,,b]"))) | |
79884bdceee1adb38b25fe99197466a1a28bc0807dc4cb02f373fb0c3f86a357 | diku-dk/futhark | Lambdas.hs | module Futhark.Internalise.Lambdas
( InternaliseLambda,
internaliseFoldLambda,
internalisePartitionLambda,
)
where
import Futhark.IR.SOACS as I
import Futhark.Internalise.AccurateSizes
import Futhark.Internalise.Monad
import Language.Futhark as E
-- | A function for internalising lambdas.
type InternaliseLambda =
E.Exp -> [I.Type] -> InternaliseM ([I.LParam SOACS], I.Body SOACS, [I.Type])
internaliseFoldLambda ::
InternaliseLambda ->
E.Exp ->
[I.Type] ->
[I.Type] ->
InternaliseM (I.Lambda SOACS)
internaliseFoldLambda internaliseLambda lam acctypes arrtypes = do
let rowtypes = map I.rowType arrtypes
(params, body, rettype) <- internaliseLambda lam $ acctypes ++ rowtypes
let rettype' =
[ t `I.setArrayShape` I.arrayShape shape
| (t, shape) <- zip rettype acctypes
]
-- The result of the body must have the exact same shape as the
-- initial accumulator.
mkLambda params $
ensureResultShape
(ErrorMsg [ErrorString "shape of result does not match shape of initial value"])
(srclocOf lam)
rettype'
=<< bodyBind body
Given @k@ lambdas , this will return a lambda that returns an
( k+2)-element tuple of integers . The first element is the
equivalence class ID in the range [ 0,k ] . The remaining are all zero
except for possibly one element .
internalisePartitionLambda ::
InternaliseLambda ->
Int ->
E.Exp ->
[I.SubExp] ->
InternaliseM (I.Lambda SOACS)
internalisePartitionLambda internaliseLambda k lam args = do
argtypes <- mapM I.subExpType args
let rowtypes = map I.rowType argtypes
(params, body, _) <- internaliseLambda lam rowtypes
body' <-
localScope (scopeOfLParams params) $
lambdaWithIncrement body
pure $ I.Lambda params body' rettype
where
rettype = replicate (k + 2) $ I.Prim int64
result i =
map constant $
fromIntegral i
: (replicate i 0 ++ [1 :: Int64] ++ replicate (k - i) 0)
mkResult _ i | i >= k = pure $ result i
mkResult eq_class i = do
is_i <-
letSubExp "is_i" $
BasicOp $
CmpOp (CmpEq int64) eq_class $
intConst Int64 $
toInteger i
letTupExp' "part_res"
=<< eIf
(eSubExp is_i)
(pure $ resultBody $ result i)
(resultBody <$> mkResult eq_class (i + 1))
lambdaWithIncrement :: I.Body SOACS -> InternaliseM (I.Body SOACS)
lambdaWithIncrement lam_body = runBodyBuilder $ do
eq_class <- resSubExp . head <$> bodyBind lam_body
resultBody <$> mkResult eq_class 0
| null | https://raw.githubusercontent.com/diku-dk/futhark/98e4a75e4de7042afe030837084764bbf3c6c66e/src/Futhark/Internalise/Lambdas.hs | haskell | | A function for internalising lambdas.
The result of the body must have the exact same shape as the
initial accumulator. | module Futhark.Internalise.Lambdas
( InternaliseLambda,
internaliseFoldLambda,
internalisePartitionLambda,
)
where
import Futhark.IR.SOACS as I
import Futhark.Internalise.AccurateSizes
import Futhark.Internalise.Monad
import Language.Futhark as E
type InternaliseLambda =
E.Exp -> [I.Type] -> InternaliseM ([I.LParam SOACS], I.Body SOACS, [I.Type])
internaliseFoldLambda ::
InternaliseLambda ->
E.Exp ->
[I.Type] ->
[I.Type] ->
InternaliseM (I.Lambda SOACS)
internaliseFoldLambda internaliseLambda lam acctypes arrtypes = do
let rowtypes = map I.rowType arrtypes
(params, body, rettype) <- internaliseLambda lam $ acctypes ++ rowtypes
let rettype' =
[ t `I.setArrayShape` I.arrayShape shape
| (t, shape) <- zip rettype acctypes
]
mkLambda params $
ensureResultShape
(ErrorMsg [ErrorString "shape of result does not match shape of initial value"])
(srclocOf lam)
rettype'
=<< bodyBind body
Given @k@ lambdas , this will return a lambda that returns an
( k+2)-element tuple of integers . The first element is the
equivalence class ID in the range [ 0,k ] . The remaining are all zero
except for possibly one element .
internalisePartitionLambda ::
InternaliseLambda ->
Int ->
E.Exp ->
[I.SubExp] ->
InternaliseM (I.Lambda SOACS)
internalisePartitionLambda internaliseLambda k lam args = do
argtypes <- mapM I.subExpType args
let rowtypes = map I.rowType argtypes
(params, body, _) <- internaliseLambda lam rowtypes
body' <-
localScope (scopeOfLParams params) $
lambdaWithIncrement body
pure $ I.Lambda params body' rettype
where
rettype = replicate (k + 2) $ I.Prim int64
result i =
map constant $
fromIntegral i
: (replicate i 0 ++ [1 :: Int64] ++ replicate (k - i) 0)
mkResult _ i | i >= k = pure $ result i
mkResult eq_class i = do
is_i <-
letSubExp "is_i" $
BasicOp $
CmpOp (CmpEq int64) eq_class $
intConst Int64 $
toInteger i
letTupExp' "part_res"
=<< eIf
(eSubExp is_i)
(pure $ resultBody $ result i)
(resultBody <$> mkResult eq_class (i + 1))
lambdaWithIncrement :: I.Body SOACS -> InternaliseM (I.Body SOACS)
lambdaWithIncrement lam_body = runBodyBuilder $ do
eq_class <- resSubExp . head <$> bodyBind lam_body
resultBody <$> mkResult eq_class 0
|
6d3d6a4d2bf9f722ef6e27756330c107f86ae400b942ee7aa8536ee704fb1c13 | exoscale/clojure-kubernetes-client | v1_lifecycle.clj | (ns clojure-kubernetes-client.specs.v1-lifecycle
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-handler :refer :all]
[clojure-kubernetes-client.specs.v1-handler :refer :all]
)
(:import (java.io File)))
(declare v1-lifecycle-data v1-lifecycle)
(def v1-lifecycle-data
{
(ds/opt :postStart) v1-handler
(ds/opt :preStop) v1-handler
})
(def v1-lifecycle
(ds/spec
{:name ::v1-lifecycle
:spec v1-lifecycle-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_lifecycle.clj | clojure | (ns clojure-kubernetes-client.specs.v1-lifecycle
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-handler :refer :all]
[clojure-kubernetes-client.specs.v1-handler :refer :all]
)
(:import (java.io File)))
(declare v1-lifecycle-data v1-lifecycle)
(def v1-lifecycle-data
{
(ds/opt :postStart) v1-handler
(ds/opt :preStop) v1-handler
})
(def v1-lifecycle
(ds/spec
{:name ::v1-lifecycle
:spec v1-lifecycle-data}))
| |
3eb4eac0fa956c75353d256926032fc7827b4b5151d16d2831d43e25c016e164 | namin/inc | tests-2.8-req.scm |
(add-tests-with-string-output "symbols"
[(symbol? 'foo) => "#t\n"]
[(symbol? '()) => "#f\n"]
[(symbol? "") => "#f\n"]
[(symbol? '(1 2)) => "#f\n"]
[(symbol? '#()) => "#f\n"]
[(symbol? (lambda (x) x)) => "#f\n"]
[(symbol? 'foo) => "#t\n"]
[(string? 'foo) => "#f\n"]
[(pair? 'foo) => "#f\n"]
[(vector? 'foo) => "#f\n"]
[(null? 'foo) => "#f\n"]
[(boolean? 'foo) => "#f\n"]
[(procedure? 'foo) => "#f\n"]
[(eq? 'foo 'bar) => "#f\n"]
[(eq? 'foo 'foo) => "#t\n"]
['foo => "foo\n"]
['(foo bar baz) => "(foo bar baz)\n"]
['(foo foo foo foo foo foo foo foo foo foo foo)
=> "(foo foo foo foo foo foo foo foo foo foo foo)\n"]
)
| null | https://raw.githubusercontent.com/namin/inc/3f683935e290848485f8d4d165a4f727f6658d1d/src/tests-2.8-req.scm | scheme |
(add-tests-with-string-output "symbols"
[(symbol? 'foo) => "#t\n"]
[(symbol? '()) => "#f\n"]
[(symbol? "") => "#f\n"]
[(symbol? '(1 2)) => "#f\n"]
[(symbol? '#()) => "#f\n"]
[(symbol? (lambda (x) x)) => "#f\n"]
[(symbol? 'foo) => "#t\n"]
[(string? 'foo) => "#f\n"]
[(pair? 'foo) => "#f\n"]
[(vector? 'foo) => "#f\n"]
[(null? 'foo) => "#f\n"]
[(boolean? 'foo) => "#f\n"]
[(procedure? 'foo) => "#f\n"]
[(eq? 'foo 'bar) => "#f\n"]
[(eq? 'foo 'foo) => "#t\n"]
['foo => "foo\n"]
['(foo bar baz) => "(foo bar baz)\n"]
['(foo foo foo foo foo foo foo foo foo foo foo)
=> "(foo foo foo foo foo foo foo foo foo foo foo)\n"]
)
| |
eee510ace605043b5302c6eb6dd735cd621711f1d4ea9c5745096b4b1357d0ee | jepsen-io/jepsen | version_divergence.clj | (ns jepsen.crate.version-divergence
"Writes a series of unique integer values to a table whilst causing network
partitions and healing the network every 2 minutes.
We will verify that each _version of a given row identifies a single value."
(:refer-clojure :exclude [test])
(:require [jepsen [core :as jepsen]
[checker :as checker]
[cli :as cli]
[client :as client]
[generator :as gen]
[independent :as independent]
[nemesis :as nemesis]
[net :as net]
[reconnect :as rc]
[tests :as tests]
[util :as util :refer [timeout]]
[os :as os]]
[jepsen.os.debian :as debian]
[jepsen.checker.timeline :as timeline]
[jepsen.control.util :as cu]
[jepsen.control.net :as cnet]
[jepsen.crate.core :as c]
[clojure.string :as str]
[clojure.java.jdbc :as j]
[clojure.tools.logging :refer [info]]
[knossos.op :as op])
(:import (io.crate.shade.org.postgresql.util PSQLException)))
(defrecord VersionDivergenceClient [tbl-created? conn]
client/Client
(setup! [this test])
(open! [this test node]
(let [conn (c/jdbc-client node)]
(info node "Connected")
;; Everyone's gotta block until we've made the table.
(locking tbl-created?
(when (compare-and-set! tbl-created? false true)
(c/with-conn [c conn]
(j/execute! c ["drop table if exists registers"])
(info node "Creating table registers")
(j/execute! c
["create table if not exists registers (
id integer primary key,
value integer)"])
(j/execute! c
["alter table registers
set (number_of_replicas = \"0-all\")"]))))
(assoc this :conn conn)))
(invoke! [this test op]
(c/with-exception->op op
(c/with-conn [c conn]
(c/with-timeout
(try
(c/with-txn [c c]
(let [[k v] (:value op)]
(case (:f op)
:read (->> (c/query c ["select value, \"_version\"
from registers where id = ?" k])
first
(independent/tuple k)
(assoc op :type :ok, :value))
:write (let [res (j/execute! c
["insert into registers (id, value)
values (?, ?)
on duplicate key update
value = VALUES(value)" k v]
{:timeout c/timeout-delay})]
(assoc op :type :ok)))))
(catch PSQLException e
(cond
(and (= 0 (.getErrorCode e))
(re-find #"blocked by: \[.+no master\];" (str e)))
(assoc op :type :fail, :error :no-master)
(and (= 0 (.getErrorCode e))
(re-find #"rejected execution" (str e)))
(do ; Back off a bit
(Thread/sleep 1000)
(assoc op :type :info, :error :rejected-execution))
:else
(throw e))))))))
(close! [this test])
(teardown! [this test]
(rc/close! conn)))
(defn multiversion-checker
"Ensures that every _version for a read has the *same* value."
[]
(reify checker/Checker
(check [_ test model history opts]
(let [reads (->> history
(filter op/ok?)
(filter #(= :read (:f %)))
(map :value)
(group-by :_version))
multis (remove (fn [[k vs]]
(= 1 (count (set (map :value vs)))))
reads)]
{:valid? (empty? multis)
:multis multis}))))
(defn r [] {:type :invoke, :f :read, :value nil})
(defn w []
(->> (iterate inc 0)
(map (fn [x] {:type :invoke, :f :write, :value x}))
gen/seq))
(defn test
[opts]
(merge tests/noop-test
{:name "version-divergence"
:os debian/os
:db (c/db (:tarball opts))
:client (VersionDivergenceClient. (atom false) nil)
:checker (checker/compose
{:multi (independent/checker (multiversion-checker))
:timeline (timeline/html)
:perf (checker/perf)})
:concurrency 100
:nemesis (nemesis/partition-random-halves)
:generator (->> (independent/concurrent-generator
10
(range)
(fn [id]
(->> (gen/reserve 5 (r) (w)))))
(gen/nemesis
(gen/seq (cycle [(gen/sleep 120)
{:type :info, :f :start}
(gen/sleep 120)
{:type :info, :f :stop}])))
(gen/time-limit 360))}
opts))
| null | https://raw.githubusercontent.com/jepsen-io/jepsen/a75d5a50dd5fa8d639a622c124bf61253460b754/crate/src/jepsen/crate/version_divergence.clj | clojure | Everyone's gotta block until we've made the table.
Back off a bit | (ns jepsen.crate.version-divergence
"Writes a series of unique integer values to a table whilst causing network
partitions and healing the network every 2 minutes.
We will verify that each _version of a given row identifies a single value."
(:refer-clojure :exclude [test])
(:require [jepsen [core :as jepsen]
[checker :as checker]
[cli :as cli]
[client :as client]
[generator :as gen]
[independent :as independent]
[nemesis :as nemesis]
[net :as net]
[reconnect :as rc]
[tests :as tests]
[util :as util :refer [timeout]]
[os :as os]]
[jepsen.os.debian :as debian]
[jepsen.checker.timeline :as timeline]
[jepsen.control.util :as cu]
[jepsen.control.net :as cnet]
[jepsen.crate.core :as c]
[clojure.string :as str]
[clojure.java.jdbc :as j]
[clojure.tools.logging :refer [info]]
[knossos.op :as op])
(:import (io.crate.shade.org.postgresql.util PSQLException)))
(defrecord VersionDivergenceClient [tbl-created? conn]
client/Client
(setup! [this test])
(open! [this test node]
(let [conn (c/jdbc-client node)]
(info node "Connected")
(locking tbl-created?
(when (compare-and-set! tbl-created? false true)
(c/with-conn [c conn]
(j/execute! c ["drop table if exists registers"])
(info node "Creating table registers")
(j/execute! c
["create table if not exists registers (
id integer primary key,
value integer)"])
(j/execute! c
["alter table registers
set (number_of_replicas = \"0-all\")"]))))
(assoc this :conn conn)))
(invoke! [this test op]
(c/with-exception->op op
(c/with-conn [c conn]
(c/with-timeout
(try
(c/with-txn [c c]
(let [[k v] (:value op)]
(case (:f op)
:read (->> (c/query c ["select value, \"_version\"
from registers where id = ?" k])
first
(independent/tuple k)
(assoc op :type :ok, :value))
:write (let [res (j/execute! c
["insert into registers (id, value)
values (?, ?)
on duplicate key update
value = VALUES(value)" k v]
{:timeout c/timeout-delay})]
(assoc op :type :ok)))))
(catch PSQLException e
(cond
(and (= 0 (.getErrorCode e))
(re-find #"blocked by: \[.+no master\];" (str e)))
(assoc op :type :fail, :error :no-master)
(and (= 0 (.getErrorCode e))
(re-find #"rejected execution" (str e)))
(Thread/sleep 1000)
(assoc op :type :info, :error :rejected-execution))
:else
(throw e))))))))
(close! [this test])
(teardown! [this test]
(rc/close! conn)))
(defn multiversion-checker
"Ensures that every _version for a read has the *same* value."
[]
(reify checker/Checker
(check [_ test model history opts]
(let [reads (->> history
(filter op/ok?)
(filter #(= :read (:f %)))
(map :value)
(group-by :_version))
multis (remove (fn [[k vs]]
(= 1 (count (set (map :value vs)))))
reads)]
{:valid? (empty? multis)
:multis multis}))))
(defn r [] {:type :invoke, :f :read, :value nil})
(defn w []
(->> (iterate inc 0)
(map (fn [x] {:type :invoke, :f :write, :value x}))
gen/seq))
(defn test
[opts]
(merge tests/noop-test
{:name "version-divergence"
:os debian/os
:db (c/db (:tarball opts))
:client (VersionDivergenceClient. (atom false) nil)
:checker (checker/compose
{:multi (independent/checker (multiversion-checker))
:timeline (timeline/html)
:perf (checker/perf)})
:concurrency 100
:nemesis (nemesis/partition-random-halves)
:generator (->> (independent/concurrent-generator
10
(range)
(fn [id]
(->> (gen/reserve 5 (r) (w)))))
(gen/nemesis
(gen/seq (cycle [(gen/sleep 120)
{:type :info, :f :start}
(gen/sleep 120)
{:type :info, :f :stop}])))
(gen/time-limit 360))}
opts))
|
38038496dd04e568892d101e67ce56c4028d8b5a27b126f99ef640a28475486a | haskell-repa/repa | IO.hs |
module Data.Repa.Flow.Generic.IO
( -- * Buckets
module Data.Repa.Flow.IO.Bucket
-- * Sourcing
, sourceBytes
, sourceChars
, sourceChunks
, sourceRecords
, sourceLinesFormat
, sourceLinesFormatFromLazyByteString
-- * Sinking
, sinkBytes
, sinkChars
, sinkLines
-- * Sieving
, sieve_o
-- * Tables
, sourceCSV
, sourceTSV)
where
import Data.Repa.Flow.IO.Bucket
import Data.Repa.Flow.Generic.IO.Base as F
import Data.Repa.Flow.Generic.IO.XSV as F
import Data.Repa.Flow.Generic.IO.Lines as F
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-flow/Data/Repa/Flow/Generic/IO.hs | haskell | * Buckets
* Sourcing
* Sinking
* Sieving
* Tables |
module Data.Repa.Flow.Generic.IO
module Data.Repa.Flow.IO.Bucket
, sourceBytes
, sourceChars
, sourceChunks
, sourceRecords
, sourceLinesFormat
, sourceLinesFormatFromLazyByteString
, sinkBytes
, sinkChars
, sinkLines
, sieve_o
, sourceCSV
, sourceTSV)
where
import Data.Repa.Flow.IO.Bucket
import Data.Repa.Flow.Generic.IO.Base as F
import Data.Repa.Flow.Generic.IO.XSV as F
import Data.Repa.Flow.Generic.IO.Lines as F
|
5dc1475d6272a3d923500b7aa6e87143534c831cbdc8358f9a095e089800243e | ekmett/ekmett.github.com | Algebra.hs | -----------------------------------------------------------------------------
-- |
-- Module : Control.Functor.Algebra
Copyright : ( C ) 2008
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
Algebras , Coalgebras , Bialgebras , and Dialgebras and their ( co)monadic
-- variants
----------------------------------------------------------------------------
module Control.Functor.Algebra
( Dialgebra, GDialgebra
, Bialgebra, GBialgebra
, Algebra, GAlgebra
, Coalgebra, GCoalgebra
, Trialgebra
, liftAlgebra
, liftCoalgebra
, liftDialgebra
, fromCoalgebra
, fromAlgebra
, fromBialgebra
) where
import Control.Comonad
import Control.Monad.Identity
import Control.Functor
import Control.Functor.Extras
import Control.Functor.Combinators.Lift
| F - G - bialgebras are representable by @DiAlg ( f : + : Identity ) ( Identity : + : g ) a@
-- and so add no expressive power, but are a lot more convenient.
type Bialgebra f g a = (Algebra f a, Coalgebra g a)
type GBialgebra f g w m a = (GAlgebra f w a, GCoalgebra g m a)
| trialgebras for indexed data types
type Trialgebra f g h a = (Algebra f a, Dialgebra g h a)
-- | F-Algebras
type Algebra f a = f a -> a
-- | F-Coalgebras
type Coalgebra f a = a -> f a
-- | F-W-Comonadic Algebras for a given comonad W
type GAlgebra f w a = f (w a) -> a
-- | F-M-Monadic Coalgebras for a given monad M
type GCoalgebra f m a = a -> f (m a)
-- | Turn an F-algebra into a F-W-algebra by throwing away the comonad
liftAlgebra :: (Functor f, Comonad w) => Algebra f :~> GAlgebra f w
liftAlgebra phi = phi . fmap extract
| Turn a F - coalgebra into a F - M - coalgebra by returning into a monad
liftCoalgebra :: (Functor f, Monad m) => Coalgebra f :~> GCoalgebra f m
liftCoalgebra psi = fmap return . psi
liftDialgebra :: (Functor g, Functor f, Comonad w, Monad m) => Dialgebra f g :~> GDialgebra f g w m
liftDialgebra phi = fmap return . phi . fmap extract
fromAlgebra :: Algebra f :~> Dialgebra f Identity
fromAlgebra phi = Identity . phi
fromCoalgebra :: Coalgebra f :~> Dialgebra Identity f
fromCoalgebra psi = psi . runIdentity
fromBialgebra :: Bialgebra f g :~> Dialgebra (f :*: Identity) (Identity :*: g)
fromBialgebra (phi,psi) = Lift . bimap (Identity . phi) (psi . runIdentity) . runLift
| F , G - dialgebras generalize algebras and coalgebras
NB : these definitions are actually wrong .
type Dialgebra f g a = f a -> g a
type GDialgebra f g w m a = f (w a) -> g (m a)
| null | https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/category-extras/_darcs/pristine/src/Control/Functor/Algebra.hs | haskell | ---------------------------------------------------------------------------
|
Module : Control.Functor.Algebra
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable (rank-2 polymorphism)
variants
--------------------------------------------------------------------------
and so add no expressive power, but are a lot more convenient.
| F-Algebras
| F-Coalgebras
| F-W-Comonadic Algebras for a given comonad W
| F-M-Monadic Coalgebras for a given monad M
| Turn an F-algebra into a F-W-algebra by throwing away the comonad | Copyright : ( C ) 2008
Maintainer : < >
Algebras , Coalgebras , Bialgebras , and Dialgebras and their ( co)monadic
module Control.Functor.Algebra
( Dialgebra, GDialgebra
, Bialgebra, GBialgebra
, Algebra, GAlgebra
, Coalgebra, GCoalgebra
, Trialgebra
, liftAlgebra
, liftCoalgebra
, liftDialgebra
, fromCoalgebra
, fromAlgebra
, fromBialgebra
) where
import Control.Comonad
import Control.Monad.Identity
import Control.Functor
import Control.Functor.Extras
import Control.Functor.Combinators.Lift
| F - G - bialgebras are representable by @DiAlg ( f : + : Identity ) ( Identity : + : g ) a@
type Bialgebra f g a = (Algebra f a, Coalgebra g a)
type GBialgebra f g w m a = (GAlgebra f w a, GCoalgebra g m a)
| trialgebras for indexed data types
type Trialgebra f g h a = (Algebra f a, Dialgebra g h a)
type Algebra f a = f a -> a
type Coalgebra f a = a -> f a
type GAlgebra f w a = f (w a) -> a
type GCoalgebra f m a = a -> f (m a)
liftAlgebra :: (Functor f, Comonad w) => Algebra f :~> GAlgebra f w
liftAlgebra phi = phi . fmap extract
| Turn a F - coalgebra into a F - M - coalgebra by returning into a monad
liftCoalgebra :: (Functor f, Monad m) => Coalgebra f :~> GCoalgebra f m
liftCoalgebra psi = fmap return . psi
liftDialgebra :: (Functor g, Functor f, Comonad w, Monad m) => Dialgebra f g :~> GDialgebra f g w m
liftDialgebra phi = fmap return . phi . fmap extract
fromAlgebra :: Algebra f :~> Dialgebra f Identity
fromAlgebra phi = Identity . phi
fromCoalgebra :: Coalgebra f :~> Dialgebra Identity f
fromCoalgebra psi = psi . runIdentity
fromBialgebra :: Bialgebra f g :~> Dialgebra (f :*: Identity) (Identity :*: g)
fromBialgebra (phi,psi) = Lift . bimap (Identity . phi) (psi . runIdentity) . runLift
| F , G - dialgebras generalize algebras and coalgebras
NB : these definitions are actually wrong .
type Dialgebra f g a = f a -> g a
type GDialgebra f g w m a = f (w a) -> g (m a)
|
bebaeb06e5795f283d5856fbddd162d09f85dd544624842595c874531e3671ca | seltzer1717/just-maven-clojure-archetype | core.clj | (ns com.example.sample.core)
(defn reverso [input]
(->> input reverse (apply str))) | null | https://raw.githubusercontent.com/seltzer1717/just-maven-clojure-archetype/ae748b97ffc3ae4f89f9367a6296298e1b6b09f5/src/test/resources/projects/basic/child/reference/src/main/clojure/com/example/sample/core.clj | clojure | (ns com.example.sample.core)
(defn reverso [input]
(->> input reverse (apply str))) | |
52bdfd8f4ddd966779181ba509a5e3c212af74f02b8db4569036877c82eeb87d | ghc/ghc | Arity07.hs | module F7 where
f7f = \x -> x
f7g = \z -> \y -> z+y
f7 = f7f f7g 2 3
| null | https://raw.githubusercontent.com/ghc/ghc/37cfe3c0f4fb16189bbe3bb735f758cd6e3d9157/testsuite/tests/arityanal/should_compile/Arity07.hs | haskell | module F7 where
f7f = \x -> x
f7g = \z -> \y -> z+y
f7 = f7f f7g 2 3
| |
061ad1780882f97fdf5634f24d439cb5e7f89a037ca654adcacaaba8f6edef8b | circuithub/rel8 | HKD.hs | # language AllowAmbiguousTypes #
# language DataKinds #
{-# language FlexibleContexts #-}
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language RankNTypes #
{-# language ScopedTypeVariables #-}
# language StandaloneKindSignatures #
# language TypeApplications #
{-# language TypeFamilies #-}
{-# language UndecidableInstances #-}
# language UndecidableSuperClasses #
module Rel8.Table.HKD
( HKD( HKD )
, HKDable
, BuildableHKD
, BuildHKD, buildHKD
, ConstructableHKD
, ConstructHKD, constructHKD
, DeconstructHKD, deconstructHKD
, NameHKD, nameHKD
, AggregateHKD, aggregateHKD
, HKDRep
)
where
-- base
import Data.Kind ( Constraint, Type )
import GHC.Generics ( Generic, Rep, from, to )
import GHC.TypeLits ( Symbol )
import Prelude
-- rel8
import Rel8.Aggregate ( Aggregate )
import Rel8.Column ( TColumn )
import Rel8.Expr ( Expr )
import Rel8.FCF ( Eval, Exp )
import Rel8.Kind.Algebra ( KnownAlgebra )
import Rel8.Generic.Construction
( GGBuildable
, GGBuild, ggbuild
, GGConstructable
, GGConstruct, ggconstruct
, GGDeconstruct, ggdeconstruct
, GGName, ggname
, GGAggregate, ggaggregate
)
import Rel8.Generic.Map ( GMap )
import Rel8.Generic.Record
( GRecord, GRecordable, grecord, gunrecord
, Record( Record ), unrecord
)
import Rel8.Generic.Rel8able
( Rel8able
, GColumns, gfromColumns, gtoColumns
, GFromExprs, gfromResult, gtoResult
)
import Rel8.Generic.Table
( GGSerialize, GGColumns, GAlgebra, ggfromResult, ggtoResult
)
import Rel8.Generic.Table.Record ( GTable, GContext )
import qualified Rel8.Generic.Table.Record as G
import qualified Rel8.Schema.Kind as K
import Rel8.Schema.HTable ( HTable )
import Rel8.Schema.Name ( Name )
import Rel8.Schema.Result ( Result )
import Rel8.Table
( Table, fromColumns, toColumns, fromResult, toResult
, TTable, TColumns, TContext
, TSerialize
)
type GColumnsHKD :: Type -> K.HTable
type GColumnsHKD a =
Eval (GGColumns (GAlgebra (Rep a)) TColumns (GRecord (GMap (TColumn Expr) (Rep a))))
type HKD :: Type -> K.Rel8able
newtype HKD a f = HKD (GColumnsHKD a f)
instance HKDable a => Rel8able (HKD a) where
type GColumns (HKD a) = GColumnsHKD a
type GFromExprs (HKD a) = a
gfromColumns _ = HKD
gtoColumns _ (HKD a) = a
gfromResult =
unrecord .
to .
ggfromResult
@(GAlgebra (Rep a))
@TSerialize
@TColumns
@(Eval (HKDRep a Expr))
@(Eval (HKDRep a Result))
(\(_ :: proxy x) -> fromResult @_ @x)
gtoResult =
ggtoResult
@(GAlgebra (Rep a))
@TSerialize
@TColumns
@(Eval (HKDRep a Expr))
@(Eval (HKDRep a Result))
(\(_ :: proxy x) -> toResult @_ @x) .
from .
Record
instance
( GTable (TTable f) TColumns (GRecord (GMap (TColumn f) (Rep a)))
, G.GColumns TColumns (GRecord (GMap (TColumn f) (Rep a))) ~ GColumnsHKD a
, GContext TContext (GRecord (GMap (TColumn f) (Rep a))) ~ f
, GRecordable (GMap (TColumn f) (Rep a))
)
=> Generic (HKD a f)
where
type Rep (HKD a f) = GMap (TColumn f) (Rep a)
from =
gunrecord @(GMap (TColumn f) (Rep a)) .
G.gfromColumns
@(TTable f)
@TColumns
fromColumns .
(\(HKD a) -> a)
to =
HKD .
G.gtoColumns
@(TTable f)
@TColumns
toColumns .
grecord @(GMap (TColumn f) (Rep a))
type HKDable :: Type -> Constraint
class
( Generic (Record a)
, HTable (GColumns (HKD a))
, KnownAlgebra (GAlgebra (Rep a))
, Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
, GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
)
=> HKDable a
instance
( Generic (Record a)
, HTable (GColumns (HKD a))
, KnownAlgebra (GAlgebra (Rep a))
, Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
, GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
)
=> HKDable a
type Top_ :: Constraint
class Top_
instance Top_
data Top :: Type -> Exp Constraint
type instance Eval (Top _) = Top_
type BuildableHKD :: Type -> Symbol -> Constraint
class GGBuildable (GAlgebra (Rep a)) name (HKDRep a) => BuildableHKD a name
instance GGBuildable (GAlgebra (Rep a)) name (HKDRep a) => BuildableHKD a name
type BuildHKD :: Type -> Symbol -> Type
type BuildHKD a name = GGBuild (GAlgebra (Rep a)) name (HKDRep a) (HKD a Expr)
buildHKD :: forall a name. BuildableHKD a name => BuildHKD a name
buildHKD =
ggbuild @(GAlgebra (Rep a)) @name @(HKDRep a) @(HKD a Expr) HKD
type ConstructableHKD :: Type -> Constraint
class GGConstructable (GAlgebra (Rep a)) (HKDRep a) => ConstructableHKD a
instance GGConstructable (GAlgebra (Rep a)) (HKDRep a) => ConstructableHKD a
type ConstructHKD :: Type -> Type
type ConstructHKD a = forall r. GGConstruct (GAlgebra (Rep a)) (HKDRep a) r
constructHKD :: forall a. ConstructableHKD a => ConstructHKD a -> HKD a Expr
constructHKD f =
ggconstruct @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) HKD
(f @(HKD a Expr))
type DeconstructHKD :: Type -> Type -> Type
type DeconstructHKD a r = GGDeconstruct (GAlgebra (Rep a)) (HKDRep a) (HKD a Expr) r
deconstructHKD :: forall a r. (ConstructableHKD a, Table Expr r)
=> DeconstructHKD a r
deconstructHKD = ggdeconstruct @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) @r (\(HKD a) -> a)
type NameHKD :: Type -> Type
type NameHKD a = GGName (GAlgebra (Rep a)) (HKDRep a) (HKD a Name)
nameHKD :: forall a. ConstructableHKD a => NameHKD a
nameHKD = ggname @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Name) HKD
type AggregateHKD :: Type -> Type
type AggregateHKD a = forall r. GGAggregate (GAlgebra (Rep a)) (HKDRep a) r
aggregateHKD :: forall a. ConstructableHKD a
=> AggregateHKD a -> HKD a Expr -> HKD a Aggregate
aggregateHKD f =
ggaggregate @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) @(HKD a Aggregate) HKD (\(HKD a) -> a)
(f @(HKD a Aggregate))
data HKDRep :: Type -> K.Context -> Exp (Type -> Type)
type instance Eval (HKDRep a context) =
GRecord (GMap (TColumn context) (Rep a))
| null | https://raw.githubusercontent.com/circuithub/rel8/2a25126e214c1171c3d0c2d12d5a14ca831a266c/src/Rel8/Table/HKD.hs | haskell | # language FlexibleContexts #
# language ScopedTypeVariables #
# language TypeFamilies #
# language UndecidableInstances #
base
rel8 | # language AllowAmbiguousTypes #
# language DataKinds #
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language RankNTypes #
# language StandaloneKindSignatures #
# language TypeApplications #
# language UndecidableSuperClasses #
module Rel8.Table.HKD
( HKD( HKD )
, HKDable
, BuildableHKD
, BuildHKD, buildHKD
, ConstructableHKD
, ConstructHKD, constructHKD
, DeconstructHKD, deconstructHKD
, NameHKD, nameHKD
, AggregateHKD, aggregateHKD
, HKDRep
)
where
import Data.Kind ( Constraint, Type )
import GHC.Generics ( Generic, Rep, from, to )
import GHC.TypeLits ( Symbol )
import Prelude
import Rel8.Aggregate ( Aggregate )
import Rel8.Column ( TColumn )
import Rel8.Expr ( Expr )
import Rel8.FCF ( Eval, Exp )
import Rel8.Kind.Algebra ( KnownAlgebra )
import Rel8.Generic.Construction
( GGBuildable
, GGBuild, ggbuild
, GGConstructable
, GGConstruct, ggconstruct
, GGDeconstruct, ggdeconstruct
, GGName, ggname
, GGAggregate, ggaggregate
)
import Rel8.Generic.Map ( GMap )
import Rel8.Generic.Record
( GRecord, GRecordable, grecord, gunrecord
, Record( Record ), unrecord
)
import Rel8.Generic.Rel8able
( Rel8able
, GColumns, gfromColumns, gtoColumns
, GFromExprs, gfromResult, gtoResult
)
import Rel8.Generic.Table
( GGSerialize, GGColumns, GAlgebra, ggfromResult, ggtoResult
)
import Rel8.Generic.Table.Record ( GTable, GContext )
import qualified Rel8.Generic.Table.Record as G
import qualified Rel8.Schema.Kind as K
import Rel8.Schema.HTable ( HTable )
import Rel8.Schema.Name ( Name )
import Rel8.Schema.Result ( Result )
import Rel8.Table
( Table, fromColumns, toColumns, fromResult, toResult
, TTable, TColumns, TContext
, TSerialize
)
type GColumnsHKD :: Type -> K.HTable
type GColumnsHKD a =
Eval (GGColumns (GAlgebra (Rep a)) TColumns (GRecord (GMap (TColumn Expr) (Rep a))))
type HKD :: Type -> K.Rel8able
newtype HKD a f = HKD (GColumnsHKD a f)
instance HKDable a => Rel8able (HKD a) where
type GColumns (HKD a) = GColumnsHKD a
type GFromExprs (HKD a) = a
gfromColumns _ = HKD
gtoColumns _ (HKD a) = a
gfromResult =
unrecord .
to .
ggfromResult
@(GAlgebra (Rep a))
@TSerialize
@TColumns
@(Eval (HKDRep a Expr))
@(Eval (HKDRep a Result))
(\(_ :: proxy x) -> fromResult @_ @x)
gtoResult =
ggtoResult
@(GAlgebra (Rep a))
@TSerialize
@TColumns
@(Eval (HKDRep a Expr))
@(Eval (HKDRep a Result))
(\(_ :: proxy x) -> toResult @_ @x) .
from .
Record
instance
( GTable (TTable f) TColumns (GRecord (GMap (TColumn f) (Rep a)))
, G.GColumns TColumns (GRecord (GMap (TColumn f) (Rep a))) ~ GColumnsHKD a
, GContext TContext (GRecord (GMap (TColumn f) (Rep a))) ~ f
, GRecordable (GMap (TColumn f) (Rep a))
)
=> Generic (HKD a f)
where
type Rep (HKD a f) = GMap (TColumn f) (Rep a)
from =
gunrecord @(GMap (TColumn f) (Rep a)) .
G.gfromColumns
@(TTable f)
@TColumns
fromColumns .
(\(HKD a) -> a)
to =
HKD .
G.gtoColumns
@(TTable f)
@TColumns
toColumns .
grecord @(GMap (TColumn f) (Rep a))
type HKDable :: Type -> Constraint
class
( Generic (Record a)
, HTable (GColumns (HKD a))
, KnownAlgebra (GAlgebra (Rep a))
, Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
, GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
)
=> HKDable a
instance
( Generic (Record a)
, HTable (GColumns (HKD a))
, KnownAlgebra (GAlgebra (Rep a))
, Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
, GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
)
=> HKDable a
type Top_ :: Constraint
class Top_
instance Top_
data Top :: Type -> Exp Constraint
type instance Eval (Top _) = Top_
type BuildableHKD :: Type -> Symbol -> Constraint
class GGBuildable (GAlgebra (Rep a)) name (HKDRep a) => BuildableHKD a name
instance GGBuildable (GAlgebra (Rep a)) name (HKDRep a) => BuildableHKD a name
type BuildHKD :: Type -> Symbol -> Type
type BuildHKD a name = GGBuild (GAlgebra (Rep a)) name (HKDRep a) (HKD a Expr)
buildHKD :: forall a name. BuildableHKD a name => BuildHKD a name
buildHKD =
ggbuild @(GAlgebra (Rep a)) @name @(HKDRep a) @(HKD a Expr) HKD
type ConstructableHKD :: Type -> Constraint
class GGConstructable (GAlgebra (Rep a)) (HKDRep a) => ConstructableHKD a
instance GGConstructable (GAlgebra (Rep a)) (HKDRep a) => ConstructableHKD a
type ConstructHKD :: Type -> Type
type ConstructHKD a = forall r. GGConstruct (GAlgebra (Rep a)) (HKDRep a) r
constructHKD :: forall a. ConstructableHKD a => ConstructHKD a -> HKD a Expr
constructHKD f =
ggconstruct @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) HKD
(f @(HKD a Expr))
type DeconstructHKD :: Type -> Type -> Type
type DeconstructHKD a r = GGDeconstruct (GAlgebra (Rep a)) (HKDRep a) (HKD a Expr) r
deconstructHKD :: forall a r. (ConstructableHKD a, Table Expr r)
=> DeconstructHKD a r
deconstructHKD = ggdeconstruct @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) @r (\(HKD a) -> a)
type NameHKD :: Type -> Type
type NameHKD a = GGName (GAlgebra (Rep a)) (HKDRep a) (HKD a Name)
nameHKD :: forall a. ConstructableHKD a => NameHKD a
nameHKD = ggname @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Name) HKD
type AggregateHKD :: Type -> Type
type AggregateHKD a = forall r. GGAggregate (GAlgebra (Rep a)) (HKDRep a) r
aggregateHKD :: forall a. ConstructableHKD a
=> AggregateHKD a -> HKD a Expr -> HKD a Aggregate
aggregateHKD f =
ggaggregate @(GAlgebra (Rep a)) @(HKDRep a) @(HKD a Expr) @(HKD a Aggregate) HKD (\(HKD a) -> a)
(f @(HKD a Aggregate))
data HKDRep :: Type -> K.Context -> Exp (Type -> Type)
type instance Eval (HKDRep a context) =
GRecord (GMap (TColumn context) (Rep a))
|
a8f4e4d49596f60ffa8c6c56cdd2bd1b4b29b86913b73d051b817969d09e6f38 | wireless-net/erlang-nommu | slave.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(slave).
%% If the macro DEBUG is defined during compilation,
debug printouts are done through erlang : display/1 .
Activate this feature by starting the compiler
%% with> erlc -DDEBUG ...
%% or by> setenv ERL_COMPILER_FLAGS DEBUG
before running make ( in the OTP make system )
%% (the example is for tcsh)
-export([pseudo/1,
pseudo/2,
start/1, start/2, start/3,
start/5,
start_link/1, start_link/2, start_link/3,
stop/1,
relay/1]).
%% Internal exports
-export([wait_for_slave/7, slave_start/1, wait_for_master_to_die/2]).
-import(error_logger, [error_msg/2]).
-ifdef(DEBUG).
-define(dbg(Tag,Data), erlang:display({Tag,Data})).
-else.
-define(dbg(Tag,Data), true).
-endif.
%% Start a list of pseudo servers on the local node
pseudo([Master | ServerList]) ->
pseudo(Master , ServerList);
pseudo(_) ->
error_msg("No master node given to slave:pseudo/1~n",[]).
-spec pseudo(Master, ServerList) -> ok when
Master :: node(),
ServerList :: [atom()].
pseudo(_, []) -> ok;
pseudo(Master, [S|Tail]) ->
start_pseudo(S, whereis(S), Master),
pseudo(Master, Tail).
start_pseudo(Name, undefined, Master) ->
X = rpc:call(Master,erlang, whereis,[Name]),
register(Name, spawn(slave, relay, [X]));
start_pseudo(_,_,_) -> ok. %% It's already there
%% This relay can be used to relay all messages directed to a process.
-spec relay(Pid) -> no_return() when
Pid :: pid().
relay({badrpc,Reason}) ->
error_msg(" ** exiting relay server ~w :~w **~n", [self(),Reason]),
exit(Reason);
relay(undefined) ->
error_msg(" ** exiting relay server ~w **~n", [self()]),
exit(undefined);
relay(Pid) when is_pid(Pid) ->
relay1(Pid).
relay1(Pid) ->
receive
X ->
Pid ! X
end,
relay1(Pid).
start/1,2,3 --
%% start_link/1,2,3 --
%%
The start/1,2,3 functions are used to start a slave Erlang node .
%% The node on which the start/N functions are used is called the
%% master in the description below.
%%
%% If hostname is the same for the master and the slave,
the Erlang node will simply be spawned . The only requirment for
%% this to work is that the 'erl' program can be found in PATH.
%%
%% If the master and slave are on different hosts, start/N uses
the ' rsh ' program to spawn an Erlang node on the other host .
%% Alternative, if the master was started as
%% 'erl -sname xxx -rsh my_rsh...', then 'my_rsh' will be used instead
%% of 'rsh' (this is useful for systems where the rsh program is named
%% 'remsh').
%%
%% For this to work, the following conditions must be fulfilled:
%%
1 . There must be an Rsh program on computer ; if not an error
%% is returned.
%%
2 . The hosts must be configured to allowed ' rsh ' access without
%% prompts for password.
%%
%% The slave node will have its filer and user server redirected
%% to the master. When the master node dies, the slave node will
terminate . For the start_link functions , the slave node will
%% terminate also if the process which called start_link terminates.
%%
%% Returns: {ok, Name@Host} |
%% {error, timeout} |
%% {error, no_rsh} |
%% {error, {already_running, Name@Host}}
-spec start(Host) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
start(Host, Name, [], no_link).
-spec start(Host, Name) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host, Name) ->
start(Host, Name, []).
-spec start(Host, Name, Args) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Args :: string(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host, Name, Args) ->
start(Host, Name, Args, no_link).
-spec start_link(Host) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
start(Host, Name, [], self()).
-spec start_link(Host, Name) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host, Name) ->
start_link(Host, Name, []).
-spec start_link(Host, Name, Args) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Args :: string(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host, Name, Args) ->
start(Host, Name, Args, self()).
start(Host0, Name, Args, LinkTo) ->
Prog = lib:progname(),
start(Host0, Name, Args, LinkTo, Prog).
start(Host0, Name, Args, LinkTo, Prog) ->
Host =
case net_kernel:longnames() of
true -> dns(Host0);
false -> strip_host_name(to_list(Host0));
ignored -> exit(not_alive)
end,
Node = list_to_atom(lists:concat([Name, "@", Host])),
case net_adm:ping(Node) of
pang ->
start_it(Host, Name, Node, Args, LinkTo, Prog);
pong ->
{error, {already_running, Node}}
end.
%% Stops a running node.
-spec stop(Node) -> ok when
Node :: node().
stop(Node) ->
% io:format("stop(~p)~n", [Node]),
rpc:call(Node, erlang, halt, []),
ok.
%% Starts a new slave node.
start_it(Host, Name, Node, Args, LinkTo, Prog) ->
spawn(?MODULE, wait_for_slave, [self(), Host, Name, Node, Args, LinkTo,
Prog]),
receive
{result, Result} -> Result
end.
%% Waits for the slave to start.
wait_for_slave(Parent, Host, Name, Node, Args, LinkTo, Prog) ->
Waiter = register_unique_name(0),
case mk_cmd(Host, Name, Args, Waiter, Prog) of
{ok, Cmd} ->
%% io:format("Command: ~ts~n", [Cmd]),
open_port({spawn, Cmd}, [stream]),
receive
{SlavePid, slave_started} ->
unregister(Waiter),
slave_started(Parent, LinkTo, SlavePid)
after 32000 ->
%% If it seems that the node was partially started,
%% try to kill it.
Node = list_to_atom(lists:concat([Name, "@", Host])),
case net_adm:ping(Node) of
pong ->
spawn(Node, erlang, halt, []),
ok;
_ ->
ok
end,
Parent ! {result, {error, timeout}}
end;
Other ->
Parent ! {result, Other}
end.
slave_started(ReplyTo, no_link, Slave) when is_pid(Slave) ->
ReplyTo ! {result, {ok, node(Slave)}};
slave_started(ReplyTo, Master, Slave) when is_pid(Master), is_pid(Slave) ->
process_flag(trap_exit, true),
link(Master),
link(Slave),
ReplyTo ! {result, {ok, node(Slave)}},
one_way_link(Master, Slave).
This function simulates a one - way link , so that the slave node
%% will be killed if the master process terminates, but the master
%% process will not be killed if the slave node terminates.
one_way_link(Master, Slave) ->
receive
{'EXIT', Master, _Reason} ->
unlink(Slave),
Slave ! {nodedown, node()};
{'EXIT', Slave, _Reason} ->
unlink(Master);
_Other ->
one_way_link(Master, Slave)
end.
register_unique_name(Number) ->
Name = list_to_atom(lists:concat(["slave_waiter_", Number])),
case catch register(Name, self()) of
true ->
Name;
{'EXIT', {badarg, _}} ->
register_unique_name(Number+1)
end.
%% Makes up the command to start the nodes.
%% If the node should run on the local host, there is
%% no need to use rsh.
mk_cmd(Host, Name, Args, Waiter, Prog0) ->
Prog = case os:type() of
{ose,_} -> mk_ose_prog(Prog0);
_ -> quote_progname(Prog0)
end,
BasicCmd = lists:concat([Prog,
" -detached -noinput -master ", node(),
" ", long_or_short(), Name, "@", Host,
" -s slave slave_start ", node(),
" ", Waiter,
" ", Args]),
case after_char($@, atom_to_list(node())) of
Host ->
{ok, BasicCmd};
_ ->
case rsh() of
{ok, Rsh} ->
{ok, lists:concat([Rsh, " ", Host, " ", BasicCmd])};
Other ->
Other
end
end.
On OSE we have to pass the beam arguments directory to the slave
%% process. To find out what arguments that should be passed on we
%% make an assumption. All arguments after the last "--" should be
%% skipped. So given these arguments:
-Muycs256 -A 1 -- -root /mst/ -progname beam.debug.smp -- -home /mst/ -- " /mst / inetrc.conf " ' -- -name test@localhost
%% we send
-Muycs256 -A 1 -- -root /mst/ -progname beam.debug.smp -- -home /mst/ -- " /mst / inetrc.conf " ' --
%% to the slave with whatever other args that are added in mk_cmd.
mk_ose_prog(Prog) ->
SkipTail = fun("--",[]) ->
["--"];
(_,[]) ->
[];
(Arg,Args) ->
[Arg," "|Args]
end,
[Prog,tl(lists:foldr(SkipTail,[],erlang:system_info(emu_args)))].
%% This is an attempt to distinguish between spaces in the program
%% path and spaces that separate arguments. The program is quoted to
%% allow spaces in the path.
%%
%% Arguments could exist either if the executable is excplicitly given
( through start/5 ) or if the -program switch to beam is used and
includes arguments ( typically done by cerl in OTP test environment
%% in order to ensure that slave/peer nodes are started with the same
%% emulator and flags as the test node. The return from lib:progname()
%% could then typically be '/<full_path_to>/cerl -gcov').
quote_progname(Progname) ->
do_quote_progname(string:tokens(to_list(Progname)," ")).
do_quote_progname([Prog]) ->
"\""++Prog++"\"";
do_quote_progname([Prog,Arg|Args]) ->
case os:find_executable(Prog) of
false ->
do_quote_progname([Prog++" "++Arg | Args]);
_ ->
%% this one has an executable - we assume the rest are arguments
"\""++Prog++"\""++
lists:flatten(lists:map(fun(X) -> [" ",X] end, [Arg|Args]))
end.
%% Give the user an opportunity to run another program,
than the " rsh " . On HP - UX rsh is called remsh ; thus HP users
must start as erl -rsh remsh .
%%
%% Also checks that the given program exists.
%%
%% Returns: {ok, RshPath} | {error, Reason}
rsh() ->
Rsh =
case init:get_argument(rsh) of
{ok, [[Prog]]} -> Prog;
_ -> "rsh"
end,
case os:find_executable(Rsh) of
false -> {error, no_rsh};
Path -> {ok, Path}
end.
long_or_short() ->
case net_kernel:longnames() of
true -> " -name ";
false -> " -sname "
end.
%% This function will be invoked on the slave, using the -s option of erl.
%% It will wait for the master node to terminate.
slave_start([Master, Waiter]) ->
?dbg({?MODULE, slave_start}, [[Master, Waiter]]),
spawn(?MODULE, wait_for_master_to_die, [Master, Waiter]).
wait_for_master_to_die(Master, Waiter) ->
?dbg({?MODULE, wait_for_master_to_die}, [Master, Waiter]),
process_flag(trap_exit, true),
monitor_node(Master, true),
{Waiter, Master} ! {self(), slave_started},
wloop(Master).
wloop(Master) ->
receive
{nodedown, Master} ->
?dbg({?MODULE, wloop},
[[Master], {received, {nodedown, Master}}, halting_node] ),
halt();
_Other ->
wloop(Master)
end.
%% Just the short hostname, not the qualified, for convenience.
strip_host_name([]) -> [];
strip_host_name([$.|_]) -> [];
strip_host_name([H|T]) -> [H|strip_host_name(T)].
dns(H) -> {ok, Host} = net_adm:dns_hostname(H), Host.
to_list(X) when is_list(X) -> X;
to_list(X) when is_atom(X) -> atom_to_list(X).
upto(_, []) -> [];
upto(Char, [Char|_]) -> [];
upto(Char, [H|T]) -> [H|upto(Char, T)].
after_char(_, []) -> [];
after_char(Char, [Char|Rest]) -> Rest;
after_char(Char, [_|Rest]) -> after_char(Char, Rest).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/stdlib/src/slave.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
If the macro DEBUG is defined during compilation,
with> erlc -DDEBUG ...
or by> setenv ERL_COMPILER_FLAGS DEBUG
(the example is for tcsh)
Internal exports
Start a list of pseudo servers on the local node
It's already there
This relay can be used to relay all messages directed to a process.
start_link/1,2,3 --
The node on which the start/N functions are used is called the
master in the description below.
If hostname is the same for the master and the slave,
this to work is that the 'erl' program can be found in PATH.
If the master and slave are on different hosts, start/N uses
Alternative, if the master was started as
'erl -sname xxx -rsh my_rsh...', then 'my_rsh' will be used instead
of 'rsh' (this is useful for systems where the rsh program is named
'remsh').
For this to work, the following conditions must be fulfilled:
is returned.
prompts for password.
The slave node will have its filer and user server redirected
to the master. When the master node dies, the slave node will
terminate also if the process which called start_link terminates.
Returns: {ok, Name@Host} |
{error, timeout} |
{error, no_rsh} |
{error, {already_running, Name@Host}}
Stops a running node.
io:format("stop(~p)~n", [Node]),
Starts a new slave node.
Waits for the slave to start.
io:format("Command: ~ts~n", [Cmd]),
If it seems that the node was partially started,
try to kill it.
will be killed if the master process terminates, but the master
process will not be killed if the slave node terminates.
Makes up the command to start the nodes.
If the node should run on the local host, there is
no need to use rsh.
process. To find out what arguments that should be passed on we
make an assumption. All arguments after the last "--" should be
skipped. So given these arguments:
we send
to the slave with whatever other args that are added in mk_cmd.
This is an attempt to distinguish between spaces in the program
path and spaces that separate arguments. The program is quoted to
allow spaces in the path.
Arguments could exist either if the executable is excplicitly given
in order to ensure that slave/peer nodes are started with the same
emulator and flags as the test node. The return from lib:progname()
could then typically be '/<full_path_to>/cerl -gcov').
this one has an executable - we assume the rest are arguments
Give the user an opportunity to run another program,
Also checks that the given program exists.
Returns: {ok, RshPath} | {error, Reason}
This function will be invoked on the slave, using the -s option of erl.
It will wait for the master node to terminate.
Just the short hostname, not the qualified, for convenience. | Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(slave).
debug printouts are done through erlang : display/1 .
Activate this feature by starting the compiler
before running make ( in the OTP make system )
-export([pseudo/1,
pseudo/2,
start/1, start/2, start/3,
start/5,
start_link/1, start_link/2, start_link/3,
stop/1,
relay/1]).
-export([wait_for_slave/7, slave_start/1, wait_for_master_to_die/2]).
-import(error_logger, [error_msg/2]).
-ifdef(DEBUG).
-define(dbg(Tag,Data), erlang:display({Tag,Data})).
-else.
-define(dbg(Tag,Data), true).
-endif.
pseudo([Master | ServerList]) ->
pseudo(Master , ServerList);
pseudo(_) ->
error_msg("No master node given to slave:pseudo/1~n",[]).
-spec pseudo(Master, ServerList) -> ok when
Master :: node(),
ServerList :: [atom()].
pseudo(_, []) -> ok;
pseudo(Master, [S|Tail]) ->
start_pseudo(S, whereis(S), Master),
pseudo(Master, Tail).
start_pseudo(Name, undefined, Master) ->
X = rpc:call(Master,erlang, whereis,[Name]),
register(Name, spawn(slave, relay, [X]));
-spec relay(Pid) -> no_return() when
Pid :: pid().
relay({badrpc,Reason}) ->
error_msg(" ** exiting relay server ~w :~w **~n", [self(),Reason]),
exit(Reason);
relay(undefined) ->
error_msg(" ** exiting relay server ~w **~n", [self()]),
exit(undefined);
relay(Pid) when is_pid(Pid) ->
relay1(Pid).
relay1(Pid) ->
receive
X ->
Pid ! X
end,
relay1(Pid).
start/1,2,3 --
The start/1,2,3 functions are used to start a slave Erlang node .
the Erlang node will simply be spawned . The only requirment for
the ' rsh ' program to spawn an Erlang node on the other host .
1 . There must be an Rsh program on computer ; if not an error
2 . The hosts must be configured to allowed ' rsh ' access without
terminate . For the start_link functions , the slave node will
-spec start(Host) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
start(Host, Name, [], no_link).
-spec start(Host, Name) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host, Name) ->
start(Host, Name, []).
-spec start(Host, Name, Args) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Args :: string(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start(Host, Name, Args) ->
start(Host, Name, Args, no_link).
-spec start_link(Host) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host) ->
L = atom_to_list(node()),
Name = upto($@, L),
start(Host, Name, [], self()).
-spec start_link(Host, Name) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host, Name) ->
start_link(Host, Name, []).
-spec start_link(Host, Name, Args) -> {ok, Node} | {error, Reason} when
Host :: atom(),
Name :: atom(),
Args :: string(),
Node :: node(),
Reason :: timeout | no_rsh | {already_running, Node}.
start_link(Host, Name, Args) ->
start(Host, Name, Args, self()).
start(Host0, Name, Args, LinkTo) ->
Prog = lib:progname(),
start(Host0, Name, Args, LinkTo, Prog).
start(Host0, Name, Args, LinkTo, Prog) ->
Host =
case net_kernel:longnames() of
true -> dns(Host0);
false -> strip_host_name(to_list(Host0));
ignored -> exit(not_alive)
end,
Node = list_to_atom(lists:concat([Name, "@", Host])),
case net_adm:ping(Node) of
pang ->
start_it(Host, Name, Node, Args, LinkTo, Prog);
pong ->
{error, {already_running, Node}}
end.
-spec stop(Node) -> ok when
Node :: node().
stop(Node) ->
rpc:call(Node, erlang, halt, []),
ok.
start_it(Host, Name, Node, Args, LinkTo, Prog) ->
spawn(?MODULE, wait_for_slave, [self(), Host, Name, Node, Args, LinkTo,
Prog]),
receive
{result, Result} -> Result
end.
wait_for_slave(Parent, Host, Name, Node, Args, LinkTo, Prog) ->
Waiter = register_unique_name(0),
case mk_cmd(Host, Name, Args, Waiter, Prog) of
{ok, Cmd} ->
open_port({spawn, Cmd}, [stream]),
receive
{SlavePid, slave_started} ->
unregister(Waiter),
slave_started(Parent, LinkTo, SlavePid)
after 32000 ->
Node = list_to_atom(lists:concat([Name, "@", Host])),
case net_adm:ping(Node) of
pong ->
spawn(Node, erlang, halt, []),
ok;
_ ->
ok
end,
Parent ! {result, {error, timeout}}
end;
Other ->
Parent ! {result, Other}
end.
slave_started(ReplyTo, no_link, Slave) when is_pid(Slave) ->
ReplyTo ! {result, {ok, node(Slave)}};
slave_started(ReplyTo, Master, Slave) when is_pid(Master), is_pid(Slave) ->
process_flag(trap_exit, true),
link(Master),
link(Slave),
ReplyTo ! {result, {ok, node(Slave)}},
one_way_link(Master, Slave).
This function simulates a one - way link , so that the slave node
one_way_link(Master, Slave) ->
receive
{'EXIT', Master, _Reason} ->
unlink(Slave),
Slave ! {nodedown, node()};
{'EXIT', Slave, _Reason} ->
unlink(Master);
_Other ->
one_way_link(Master, Slave)
end.
register_unique_name(Number) ->
Name = list_to_atom(lists:concat(["slave_waiter_", Number])),
case catch register(Name, self()) of
true ->
Name;
{'EXIT', {badarg, _}} ->
register_unique_name(Number+1)
end.
mk_cmd(Host, Name, Args, Waiter, Prog0) ->
Prog = case os:type() of
{ose,_} -> mk_ose_prog(Prog0);
_ -> quote_progname(Prog0)
end,
BasicCmd = lists:concat([Prog,
" -detached -noinput -master ", node(),
" ", long_or_short(), Name, "@", Host,
" -s slave slave_start ", node(),
" ", Waiter,
" ", Args]),
case after_char($@, atom_to_list(node())) of
Host ->
{ok, BasicCmd};
_ ->
case rsh() of
{ok, Rsh} ->
{ok, lists:concat([Rsh, " ", Host, " ", BasicCmd])};
Other ->
Other
end
end.
On OSE we have to pass the beam arguments directory to the slave
-Muycs256 -A 1 -- -root /mst/ -progname beam.debug.smp -- -home /mst/ -- " /mst / inetrc.conf " ' -- -name test@localhost
-Muycs256 -A 1 -- -root /mst/ -progname beam.debug.smp -- -home /mst/ -- " /mst / inetrc.conf " ' --
mk_ose_prog(Prog) ->
SkipTail = fun("--",[]) ->
["--"];
(_,[]) ->
[];
(Arg,Args) ->
[Arg," "|Args]
end,
[Prog,tl(lists:foldr(SkipTail,[],erlang:system_info(emu_args)))].
( through start/5 ) or if the -program switch to beam is used and
includes arguments ( typically done by cerl in OTP test environment
quote_progname(Progname) ->
do_quote_progname(string:tokens(to_list(Progname)," ")).
do_quote_progname([Prog]) ->
"\""++Prog++"\"";
do_quote_progname([Prog,Arg|Args]) ->
case os:find_executable(Prog) of
false ->
do_quote_progname([Prog++" "++Arg | Args]);
_ ->
"\""++Prog++"\""++
lists:flatten(lists:map(fun(X) -> [" ",X] end, [Arg|Args]))
end.
than the " rsh " . On HP - UX rsh is called remsh ; thus HP users
must start as erl -rsh remsh .
rsh() ->
Rsh =
case init:get_argument(rsh) of
{ok, [[Prog]]} -> Prog;
_ -> "rsh"
end,
case os:find_executable(Rsh) of
false -> {error, no_rsh};
Path -> {ok, Path}
end.
long_or_short() ->
case net_kernel:longnames() of
true -> " -name ";
false -> " -sname "
end.
slave_start([Master, Waiter]) ->
?dbg({?MODULE, slave_start}, [[Master, Waiter]]),
spawn(?MODULE, wait_for_master_to_die, [Master, Waiter]).
wait_for_master_to_die(Master, Waiter) ->
?dbg({?MODULE, wait_for_master_to_die}, [Master, Waiter]),
process_flag(trap_exit, true),
monitor_node(Master, true),
{Waiter, Master} ! {self(), slave_started},
wloop(Master).
wloop(Master) ->
receive
{nodedown, Master} ->
?dbg({?MODULE, wloop},
[[Master], {received, {nodedown, Master}}, halting_node] ),
halt();
_Other ->
wloop(Master)
end.
strip_host_name([]) -> [];
strip_host_name([$.|_]) -> [];
strip_host_name([H|T]) -> [H|strip_host_name(T)].
dns(H) -> {ok, Host} = net_adm:dns_hostname(H), Host.
to_list(X) when is_list(X) -> X;
to_list(X) when is_atom(X) -> atom_to_list(X).
upto(_, []) -> [];
upto(Char, [Char|_]) -> [];
upto(Char, [H|T]) -> [H|upto(Char, T)].
after_char(_, []) -> [];
after_char(Char, [Char|Rest]) -> Rest;
after_char(Char, [_|Rest]) -> after_char(Char, Rest).
|
29c012504fcc7928324ee21d3c42049f15189eb368b329befebea80fcba67c44 | seagreen/ian | Megaparsec.hs | | Notes on megaparsec .
module Scratch.Megaparsec where
-- parser-combinators (-combinators):
--
" Lightweight package providing commonly useful parser combinators . "
--
Control . Monad . Combinators . NonEmpty :
--
" The module provides more efficient versions of the combinators from Control . Applicative . Combinators defined in terms of Monad and MonadPlus instead of Applicative and Alternative . When there is no difference in performance we just re - export the combinators from Control . Applicative . Combinators . "
import Control.Monad.Combinators.NonEmpty
import qualified Data.Bifunctor as Bifunctor
import Data.ByteString (ByteString)
import Data.Foldable
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Void
import Test.Hspec
import Test.Main (ProcessResult (prStdout), captureProcessResult)
Note that there are four ( ! ) modules that provide different versions
of @some@ ( six if we count re - exports ) .
--
-- The Applicative @some@, exported by Control.Applicative and Control.Applicative.Combinators.
--
The MonadPlus @some@ , exported by Control . Monad . Combinators and Text . .
--
The NonEmpty Applicative @some@ , exported by Control . Applicative . Combinators . NonEmpty .
--
The NonEmpty MonadPlus @some@ , exported by Control . Monad . Combinators . NonEmpty .
--
--
My strategy is to default to Control . Monad . Combinators . NonEmpty .
-- It has the most descriptive type signatures and greater than or equal performance
compared to Control . Applicative . Combinators . NonEmpty .
--
So we import all of Control . Monad . Combinators . NonEmpty
and then hide the clashing names from Text . .
import Text.Megaparsec hiding (endBy1, parse, sepBy1, sepEndBy1, some, someTill)
import Prelude
type Parser = Parsec Void Text
-- | megaparsec exports both @parse@ and @runParser@ (which mean the same thing).
-- We hide @parse@ to get the nice name back and then define a new one here
-- for the behavior we want in this file.
parse :: Parser a -> Text -> Either Text a
parse p =
Bifunctor.first (Text.pack . errorBundlePretty)
. runParser (p <* eof) "<input>"
Notes on redefinitions
--
-- 'Text.Megaparsec.Char.char' is a type-constrained version of 'single'.
--
-- 'Text.Megaparsec.Char.string' is a type-constrained version of 'chunk'.
--
-- 'Control.Monad.Combinators.choice' is 'asum'.
spec :: Spec
spec =
describe "megaparsec" $ do
it "running parsers" $ do
let p :: Parser Char
p = single 'a'
shouldReturnStdout :: IO () -> ByteString -> IO ()
shouldReturnStdout run expected = do
res <- captureProcessResult run
prStdout res `shouldBe` expected
When using runParser , parseTest , and
-- be aware that the last parses an @eof@ after its argument,
-- but the others don't. So you can't switch freely between them.
runParser p "<input>" "ab" `shouldBe` Right 'a'
parseTest p "ab" `shouldReturnStdout` "'a'\n"
parseMaybe p "ab" `shouldBe` Nothing
it "tokens backtracks" $ do
let p :: Parser Text
p = tokens (==) "aaa" <|> tokens (==) "aab"
parse p "aab" `shouldBe` Right "aab"
it "chunk backtracks" $ do
-- (It uses tokens under the hood).
let p :: Parser Text
p = chunk "aaa" <|> chunk "aab"
parse p "aab" `shouldBe` Right "aab"
it "some satisfy doesn't backtrack" $ do
let takeAs :: Parser Text
takeAs =
fmap (Text.pack . toList) (some (satisfy (\c -> c == 'a')))
takeAsOrBs :: Parser Text
takeAsOrBs =
fmap (Text.pack . toList) (some (satisfy (\c -> c == 'a' || c == 'b')))
parse (takeAs <|> takeAsOrBs) "aab"
`shouldBe` Left "<input>:1:3:\n |\n1 | aab\n | ^\nunexpected 'b'\nexpecting end of input\n"
| null | https://raw.githubusercontent.com/seagreen/ian/f245fb68d94299f0e3e12744e9d1549447ad529a/haskell/src/Scratch/Megaparsec.hs | haskell | parser-combinators (-combinators):
The Applicative @some@, exported by Control.Applicative and Control.Applicative.Combinators.
It has the most descriptive type signatures and greater than or equal performance
| megaparsec exports both @parse@ and @runParser@ (which mean the same thing).
We hide @parse@ to get the nice name back and then define a new one here
for the behavior we want in this file.
'Text.Megaparsec.Char.char' is a type-constrained version of 'single'.
'Text.Megaparsec.Char.string' is a type-constrained version of 'chunk'.
'Control.Monad.Combinators.choice' is 'asum'.
be aware that the last parses an @eof@ after its argument,
but the others don't. So you can't switch freely between them.
(It uses tokens under the hood). | | Notes on megaparsec .
module Scratch.Megaparsec where
" Lightweight package providing commonly useful parser combinators . "
Control . Monad . Combinators . NonEmpty :
" The module provides more efficient versions of the combinators from Control . Applicative . Combinators defined in terms of Monad and MonadPlus instead of Applicative and Alternative . When there is no difference in performance we just re - export the combinators from Control . Applicative . Combinators . "
import Control.Monad.Combinators.NonEmpty
import qualified Data.Bifunctor as Bifunctor
import Data.ByteString (ByteString)
import Data.Foldable
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Void
import Test.Hspec
import Test.Main (ProcessResult (prStdout), captureProcessResult)
Note that there are four ( ! ) modules that provide different versions
of @some@ ( six if we count re - exports ) .
The MonadPlus @some@ , exported by Control . Monad . Combinators and Text . .
The NonEmpty Applicative @some@ , exported by Control . Applicative . Combinators . NonEmpty .
The NonEmpty MonadPlus @some@ , exported by Control . Monad . Combinators . NonEmpty .
My strategy is to default to Control . Monad . Combinators . NonEmpty .
compared to Control . Applicative . Combinators . NonEmpty .
So we import all of Control . Monad . Combinators . NonEmpty
and then hide the clashing names from Text . .
import Text.Megaparsec hiding (endBy1, parse, sepBy1, sepEndBy1, some, someTill)
import Prelude
type Parser = Parsec Void Text
parse :: Parser a -> Text -> Either Text a
parse p =
Bifunctor.first (Text.pack . errorBundlePretty)
. runParser (p <* eof) "<input>"
Notes on redefinitions
spec :: Spec
spec =
describe "megaparsec" $ do
it "running parsers" $ do
let p :: Parser Char
p = single 'a'
shouldReturnStdout :: IO () -> ByteString -> IO ()
shouldReturnStdout run expected = do
res <- captureProcessResult run
prStdout res `shouldBe` expected
When using runParser , parseTest , and
runParser p "<input>" "ab" `shouldBe` Right 'a'
parseTest p "ab" `shouldReturnStdout` "'a'\n"
parseMaybe p "ab" `shouldBe` Nothing
it "tokens backtracks" $ do
let p :: Parser Text
p = tokens (==) "aaa" <|> tokens (==) "aab"
parse p "aab" `shouldBe` Right "aab"
it "chunk backtracks" $ do
let p :: Parser Text
p = chunk "aaa" <|> chunk "aab"
parse p "aab" `shouldBe` Right "aab"
it "some satisfy doesn't backtrack" $ do
let takeAs :: Parser Text
takeAs =
fmap (Text.pack . toList) (some (satisfy (\c -> c == 'a')))
takeAsOrBs :: Parser Text
takeAsOrBs =
fmap (Text.pack . toList) (some (satisfy (\c -> c == 'a' || c == 'b')))
parse (takeAs <|> takeAsOrBs) "aab"
`shouldBe` Left "<input>:1:3:\n |\n1 | aab\n | ^\nunexpected 'b'\nexpecting end of input\n"
|
1317f525f3a9c3cb1e3a064c82d1bd96c27d76894f8b169d22233feee2ad0079 | bolducp/SICP | 01.05.scm | Exercise 1.5 .
has invented a test to determine whether the interpreter he is faced with is using
applicative - order evaluation or normal - order evaluation . He defines the following two procedures :
;; (define (p) (p))
;; (define (test x y)
;; (if (= x 0)
0
;; y))
;; Then he evaluates the expression
( test 0 ( p ) )
What behavior will observe with an interpreter that uses applicative - order evaluation ?
;; What behavior will he observe with an interpreter that uses normal-order evaluation?
;; Explain your answer. (Assume that the evaluation rule for the special form if is the same
;; whether the interpreter is using normal or applicative order: The predicate expression is
evaluated first , and the result determines whether to evaluate the consequent or the alternative expression . )
;; With applicative-order, the expression will try to evaluate all of the operands so that the procedure is
fully expanded before it is reduced . Thus , it will try to evaluate p , which just calls itself in a recursive loop ,
;; and test will never end up getting invokved.
With normal order , p will never be evaluated ( and thus will never have the chance to enter into its infinite loop ) ,
because the first condition of the if - statement in test ( x = 0 ) evaluates to true and the procedure returns 0 without
;; calling p.
| null | https://raw.githubusercontent.com/bolducp/SICP/871babe9296b84b2b9648a02f9202752d21ebf93/exercises/chapter_01/1.1_exercises/01.05.scm | scheme | (define (p) (p))
(define (test x y)
(if (= x 0)
y))
Then he evaluates the expression
What behavior will he observe with an interpreter that uses normal-order evaluation?
Explain your answer. (Assume that the evaluation rule for the special form if is the same
whether the interpreter is using normal or applicative order: The predicate expression is
With applicative-order, the expression will try to evaluate all of the operands so that the procedure is
and test will never end up getting invokved.
calling p. | Exercise 1.5 .
has invented a test to determine whether the interpreter he is faced with is using
applicative - order evaluation or normal - order evaluation . He defines the following two procedures :
0
( test 0 ( p ) )
What behavior will observe with an interpreter that uses applicative - order evaluation ?
evaluated first , and the result determines whether to evaluate the consequent or the alternative expression . )
fully expanded before it is reduced . Thus , it will try to evaluate p , which just calls itself in a recursive loop ,
With normal order , p will never be evaluated ( and thus will never have the chance to enter into its infinite loop ) ,
because the first condition of the if - statement in test ( x = 0 ) evaluates to true and the procedure returns 0 without
|
aa67b1a4711a3bd873a18151271fbfee87bc139bbf7082871202ef5b63f17aa1 | langston-barrett/CoverTranslator | Add.hs | module Add where
import Property
data Nat = Zero | Succ Nat
add x Zero = x
add x (Succ y) = Succ (add x y)
The following variant is trickier to prove ( at least one case ) ...
-- add x (Succ y) = add (Succ x) y
Backwards axioms , should be pasted into the generated otter files ...
Not needed since we have restricted ourselves to total values .
-equal(c_Add_Succ , bottom ) .
-equal(c_Add_ZZero , bottom ) .
equal(app(app(f_Add_add , V_Add_x ) , app(c_Add_Succ , V_Add_y ) ) , bottom )
| equal(V_Add_y , app(c_Add_Succ , pred(V_Add_y ) ) )
| equal(V_Add_y , ) .
equal(pred(app(c_Add_Succ , X ) ) , X ) .
Not needed since we have restricted ourselves to total values.
-equal(c_Add_Succ, bottom).
-equal(c_Add_ZZero, bottom).
equal(app(app(f_Add_add, V_Add_x), app(c_Add_Succ, V_Add_y)), bottom)
| equal(V_Add_y, app(c_Add_Succ, pred(V_Add_y)))
| equal(V_Add_y, C_Add_ZZero).
equal(pred(app(c_Add_Succ, X)), X).
-}
prop_add_commutative =
forAll $ \x ->
forAll $ \y ->
add (nat_tf x) (nat_tf y) === add (nat_tf y) (nat_tf x)
Let us restrict ourselves to total , finite . Define
-- P(x, y) = add x y = add y x.
--
forall total finite x , y : : . P(x , y )
--
-- <=> Induction on y.
--
forall total finite x : : . P(x , 0 )
-- /\
forall total finite x , y : : . P(x , y ) - > P(x , Succ y )
--
< = > Induction on x in the first branch , case in the second .
--
-- P(0, 0)
-- /\
forall total finite x : : . P(x , 0 ) - > P(Succ x , 0 )
-- /\
forall total finite y : : . P(0 , y ) - > P(0 , Succ y )
-- /\
forall total finite x , y : : . P(Succ x , y ) - > P(Succ x , Succ y )
--
-- <= We can skip type information.
--
-- P(0, 0)
-- /\
-- forall x. P(x, 0) -> P(Succ x, 0)
-- /\
-- forall y. P(0, y) -> P(0, Succ y)
-- /\
forall x , y. P(Succ x , y ) - > P(Succ x , Succ y )
prop_add_commutative_base =
add Zero Zero === add Zero Zero
prop_add_commutative_step_1 =
forAll $ \x ->
add x Zero === add Zero x ==>
add (Succ x) Zero === add Zero (Succ x)
-- This step is identical to the previous one, assuming symmetric
-- equality.
prop_add_commutative_step_2 =
forAll $ \y ->
add Zero y === add y Zero ==>
add Zero (Succ y) === add (Succ y) Zero
prop_add_commutative_step_3 =
using [prop_succ_moveable] $
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add y (Succ x) ==>
add (Succ x) (Succ y) === add (Succ y) (Succ x)
-- We need a lemma:
-- Succ x + y = x + Succ y
-- Proof by induction over y.
prop_succ_moveable =
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add x (Succ y)
prop_succ_moveable_base =
forAll $ \x ->
add (Succ x) Zero === add x (Succ Zero)
prop_succ_moveable_step =
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add x (Succ y) ==>
add (Succ x) (Succ y) === add x (Succ (Succ y))
-- -- We would like to be able to have this as an axiom:
-- prop_induction_nat_total_finite :: (Nat -> Prop) -> Prop
-- prop_induction_nat_total_finite p =
p Zero /\ ( forAll $ \x - > p x = = > p ( Succ x ) ) = = >
( forAll $ \x - > p ( nat_tf x ) )
-- -- (Or possibly a variant that uses nat_tf also on the left hand
-- -- side. It should only make the proof easier, but I don't know...)
-- -- And this:
-- prop_case_nat p =
p Zero /\ ( forAll $ \x - > p ( Succ x ) ) = = >
( forAll $ \x - > p ( nat_c x ) )
-- -- Then we could state
-- prop_succ_moveable' =
-- using [prop_succ_moveable_base, prop_succ_moveable_step] $
-- prop_induction_nat_total_finite $ \y ->
forAll $ \x - >
-- add (Succ x) y === add x (Succ y)
-- -- And similarly for the main property above.
-- -- It would be even better if we could split off the base and step
-- -- cases automatically, of course. That could lead to problems, though:
-- prop_succ_moveable'' =
-- forAll_induction_nat_total_finite $ \y ->
forAll $ \x - >
-- add (Succ x) y === add x (Succ y)
-- -- We might not want want proof tactics littering our
-- -- properties. Furthermore the above is incorrect: The resulting
-- -- property should have (nat_tf y) substituted for y. How do we
-- -- check that the variable is only used like that?
-- The first approach above should work , though , and the various
-- -- induction schemes and partial identity functions can of course
-- -- be generated automatically.
Image : Finite , total plus bottom .
nat_tf :: Nat -> Nat
nat_tf Zero = Zero
nat_tf (Succ x) = Succ $! (nat_tf x)
Image : .
nat :: Nat -> Nat
nat Zero = Zero
nat (Succ x) = Succ (nat x)
Image : { _ | _ , Zero } ` union ` { Succ x | x < - Universe }
nat_c :: Nat -> Nat
nat_c Zero = Zero
nat_c (Succ x) = Succ x
| null | https://raw.githubusercontent.com/langston-barrett/CoverTranslator/4172bef9f4eede7e45dc002a70bf8c6dd9a56b5c/examples/add/Add.hs | haskell | add x (Succ y) = add (Succ x) y
P(x, y) = add x y = add y x.
<=> Induction on y.
/\
P(0, 0)
/\
/\
/\
<= We can skip type information.
P(0, 0)
/\
forall x. P(x, 0) -> P(Succ x, 0)
/\
forall y. P(0, y) -> P(0, Succ y)
/\
This step is identical to the previous one, assuming symmetric
equality.
We need a lemma:
Succ x + y = x + Succ y
Proof by induction over y.
-- We would like to be able to have this as an axiom:
prop_induction_nat_total_finite :: (Nat -> Prop) -> Prop
prop_induction_nat_total_finite p =
-- (Or possibly a variant that uses nat_tf also on the left hand
-- side. It should only make the proof easier, but I don't know...)
-- And this:
prop_case_nat p =
-- Then we could state
prop_succ_moveable' =
using [prop_succ_moveable_base, prop_succ_moveable_step] $
prop_induction_nat_total_finite $ \y ->
add (Succ x) y === add x (Succ y)
-- And similarly for the main property above.
-- It would be even better if we could split off the base and step
-- cases automatically, of course. That could lead to problems, though:
prop_succ_moveable'' =
forAll_induction_nat_total_finite $ \y ->
add (Succ x) y === add x (Succ y)
-- We might not want want proof tactics littering our
-- properties. Furthermore the above is incorrect: The resulting
-- property should have (nat_tf y) substituted for y. How do we
-- check that the variable is only used like that?
The first approach above should work , though , and the various
-- induction schemes and partial identity functions can of course
-- be generated automatically. | module Add where
import Property
data Nat = Zero | Succ Nat
add x Zero = x
add x (Succ y) = Succ (add x y)
The following variant is trickier to prove ( at least one case ) ...
Backwards axioms , should be pasted into the generated otter files ...
Not needed since we have restricted ourselves to total values .
-equal(c_Add_Succ , bottom ) .
-equal(c_Add_ZZero , bottom ) .
equal(app(app(f_Add_add , V_Add_x ) , app(c_Add_Succ , V_Add_y ) ) , bottom )
| equal(V_Add_y , app(c_Add_Succ , pred(V_Add_y ) ) )
| equal(V_Add_y , ) .
equal(pred(app(c_Add_Succ , X ) ) , X ) .
Not needed since we have restricted ourselves to total values.
-equal(c_Add_Succ, bottom).
-equal(c_Add_ZZero, bottom).
equal(app(app(f_Add_add, V_Add_x), app(c_Add_Succ, V_Add_y)), bottom)
| equal(V_Add_y, app(c_Add_Succ, pred(V_Add_y)))
| equal(V_Add_y, C_Add_ZZero).
equal(pred(app(c_Add_Succ, X)), X).
-}
prop_add_commutative =
forAll $ \x ->
forAll $ \y ->
add (nat_tf x) (nat_tf y) === add (nat_tf y) (nat_tf x)
Let us restrict ourselves to total , finite . Define
forall total finite x , y : : . P(x , y )
forall total finite x : : . P(x , 0 )
forall total finite x , y : : . P(x , y ) - > P(x , Succ y )
< = > Induction on x in the first branch , case in the second .
forall total finite x : : . P(x , 0 ) - > P(Succ x , 0 )
forall total finite y : : . P(0 , y ) - > P(0 , Succ y )
forall total finite x , y : : . P(Succ x , y ) - > P(Succ x , Succ y )
forall x , y. P(Succ x , y ) - > P(Succ x , Succ y )
prop_add_commutative_base =
add Zero Zero === add Zero Zero
prop_add_commutative_step_1 =
forAll $ \x ->
add x Zero === add Zero x ==>
add (Succ x) Zero === add Zero (Succ x)
prop_add_commutative_step_2 =
forAll $ \y ->
add Zero y === add y Zero ==>
add Zero (Succ y) === add (Succ y) Zero
prop_add_commutative_step_3 =
using [prop_succ_moveable] $
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add y (Succ x) ==>
add (Succ x) (Succ y) === add (Succ y) (Succ x)
prop_succ_moveable =
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add x (Succ y)
prop_succ_moveable_base =
forAll $ \x ->
add (Succ x) Zero === add x (Succ Zero)
prop_succ_moveable_step =
forAll $ \x ->
forAll $ \y ->
add (Succ x) y === add x (Succ y) ==>
add (Succ x) (Succ y) === add x (Succ (Succ y))
p Zero /\ ( forAll $ \x - > p x = = > p ( Succ x ) ) = = >
( forAll $ \x - > p ( nat_tf x ) )
p Zero /\ ( forAll $ \x - > p ( Succ x ) ) = = >
( forAll $ \x - > p ( nat_c x ) )
forAll $ \x - >
forAll $ \x - >
Image : Finite , total plus bottom .
nat_tf :: Nat -> Nat
nat_tf Zero = Zero
nat_tf (Succ x) = Succ $! (nat_tf x)
Image : .
nat :: Nat -> Nat
nat Zero = Zero
nat (Succ x) = Succ (nat x)
Image : { _ | _ , Zero } ` union ` { Succ x | x < - Universe }
nat_c :: Nat -> Nat
nat_c Zero = Zero
nat_c (Succ x) = Succ x
|
c0d889cb4fd8b3b678c3c458ca393cd509034af8e8104f328c73e80510e4ca55 | grin-compiler/ghc-wpc-sample-programs | Syntax.hs |
module Agda.Auto.Syntax where
import Data.IORef
import qualified Data.Set as Set
import Agda.Syntax.Common (Hiding)
import Agda.Auto.NarrowingSearch
import Agda.Utils.Impossible
-- | Unique identifiers for variable occurrences in unification.
type UId o = Metavar (Exp o) (RefInfo o)
data HintMode = HMNormal
| HMRecCall
data EqReasoningConsts o = EqReasoningConsts
{ eqrcId -- "_≡_"
, eqrcBegin -- "begin_"
, eqrcStep -- "_≡⟨_⟩_"
, eqrcEnd -- "_∎"
, eqrcSym -- "sym"
, eqrcCong -- "cong"
:: ConstRef o
}
data EqReasoningState = EqRSNone | EqRSChain | EqRSPrf1 | EqRSPrf2 | EqRSPrf3
deriving (Eq, Show)
-- | The concrete instance of the 'blk' parameter in 'Metavar'.
-- I.e., the information passed to the search control.
data RefInfo o
= RIEnv
{ rieHints :: [(ConstRef o, HintMode)]
, rieDefFreeVars :: Nat
^
-- (to make cost of using module parameters correspond to that of hints).
, rieEqReasoningConsts :: Maybe (EqReasoningConsts o)
}
| RIMainInfo
{ riMainCxtLength :: Nat
-- ^ Size of typing context in which meta was created.
, riMainType :: HNExp o
-- ^ Head normal form of type of meta.
, riMainIota :: Bool
-- ^ True if iota steps performed when normalising target type
-- (used to put cost when traversing a definition
-- by construction instantiation).
}
| RIUnifInfo [CAction o] (HNExp o)
meta environment ,
| RICopyInfo (ICExp o)
| RIIotaStep Bool -- True - semiflex
| RIInferredTypeUnknown
| RINotConstructor
| RIUsedVars [UId o] [Elr o]
| RIPickSubsvar
| RIEqRState EqReasoningState
| RICheckElim Bool -- isdep
noof proj functions
type MyPB o = PB (RefInfo o)
type MyMB a o = MB a (RefInfo o)
type Nat = Int
data MId = Id String
| NoId
-- | Abstraction with maybe a name.
--
Different from Agda , where there is also info
-- whether function is constant.
data Abs a = Abs MId a
-- | Constant signatures.
data ConstDef o = ConstDef
{ cdname :: String
-- ^ For debug printing.
, cdorigin :: o
^ Reference to the Agda constant .
, cdtype :: MExp o
-- ^ Type of constant.
, cdcont :: DeclCont o
-- ^ Constant definition.
, cddeffreevars :: Nat
-- ^ Free vars of the module where the constant is defined..
} -- contains no metas
-- | Constant definitions.
data DeclCont o
= Def Nat [Clause o] (Maybe Nat) -- maybe an index to elimand argument
maybe index to elim arg if semiflex
| Datatype [ConstRef o] -- constructors
[ConstRef o] -- projection functions (in case it is a record)
| Constructor Nat -- number of omitted args
| Postulate
type Clause o = ([Pat o], MExp o)
data Pat o
= PatConApp (ConstRef o) [Pat o]
| PatVar String
| PatExp
-- ^ Dot pattern.
{- TODO: projection patterns.
| PatProj (ConstRef o)
-- ^ Projection pattern.
-}
type ConstRef o = IORef (ConstDef o)
-- | Head of application (elimination).
data Elr o
= Var Nat
| Const (ConstRef o)
deriving (Eq)
getVar :: Elr o -> Maybe Nat
getVar (Var n) = Just n
getVar Const{} = Nothing
getConst :: Elr o -> Maybe (ConstRef o)
getConst (Const c) = Just c
getConst Var{} = Nothing
data Sort
= Set Nat
| UnknownSort
| Type
| Agsy 's internal syntax .
data Exp o
= App
{ appUId :: Maybe (UId o)
-- ^ Unique identifier of the head.
, appOK :: OKHandle (RefInfo o)
-- ^ This application has been type-checked.
, appHead :: Elr o
-- ^ Head.
, appElims :: MArgList o
-- ^ Arguments.
}
| Lam Hiding (Abs (MExp o))
-- ^ Lambda with hiding information.
| Pi (Maybe (UId o)) Hiding Bool (MExp o) (Abs (MExp o))
^ @True@ if possibly dependent ( var not known to not occur ) .
-- @False@ if non-dependent.
| Sort Sort
| AbsurdLambda Hiding
-- ^ Absurd lambda with hiding information.
dontCare :: Exp o
dontCare = Sort UnknownSort
-- | "Maybe expression": Expression or reference to meta variable.
type MExp o = MM (Exp o) (RefInfo o)
data ArgList o
= ALNil
-- ^ No more eliminations.
| ALCons Hiding (MExp o) (MArgList o)
-- ^ Application and tail.
| ALProj (MArgList o) (MM (ConstRef o) (RefInfo o)) Hiding (MArgList o)
^ proj pre args , projfcn idx , tail
| ALConPar (MArgList o)
^ Constructor parameter ( missing in Agda ) .
has monomorphic constructors .
-- Inserted to cover glitch of polymorphic constructor
applications coming from Agda
type MArgList o = MM (ArgList o) (RefInfo o)
data WithSeenUIds a o = WithSeenUIds
{ seenUIds :: [Maybe (UId o)]
, rawValue :: a
}
type HNExp o = WithSeenUIds (HNExp' o) o
data HNExp' o =
HNApp (Elr o) (ICArgList o)
| HNLam Hiding (Abs (ICExp o))
| HNPi Hiding Bool (ICExp o) (Abs (ICExp o))
| HNSort Sort
| Head - normal form of ' ICArgList ' . First entry is exposed .
--
-- Q: Why are there no projection eliminations?
data HNArgList o = HNALNil
| HNALCons Hiding (ICExp o) (ICArgList o)
| HNALConPar (ICArgList o)
-- | Lazy concatenation of argument lists under explicit substitutions.
data ICArgList o = CALNil
| CALConcat (Clos (MArgList o) o) (ICArgList o)
-- | An expression @a@ in an explicit substitution @[CAction a]@.
type ICExp o = Clos (MExp o) o
data Clos a o = Clos [CAction o] a
type CExp o = TrBr (ICExp o) o
data TrBr a o = TrBr [MExp o] a
-- | Entry of an explicit substitution.
--
-- An explicit substitution is a list of @CAction@s.
-- This is isomorphic to the usual presentation where
and @Weak@ would be constructors of exp . substs .
data CAction o
= Sub (ICExp o)
-- ^ Instantation of variable.
| Skip
-- ^ For going under a binder, often called "Lift".
| Weak Nat
-- ^ Shifting substitution (going to a larger context).
type Ctx o = [(MId, CExp o)]
type EE = IO
-- -------------------------------------------
detecteliminand :: [Clause o] -> Maybe Nat
detecteliminand cls =
case map cleli cls of
[] -> Nothing
(i:is) -> if all (i ==) is then i else Nothing
where
cleli (pats, _) = pateli 0 pats
pateli i (PatConApp _ args : pats) = if all notcon (args ++ pats) then Just i else Nothing
pateli i (_ : pats) = pateli (i + 1) pats
pateli i [] = Nothing
notcon PatConApp{} = False
notcon _ = True
detectsemiflex :: ConstRef o -> [Clause o] -> IO Bool
detectsemiflex _ _ = return False -- disabled
categorizedecl :: ConstRef o -> IO ()
categorizedecl c = do
cd <- readIORef c
case cdcont cd of
Def narg cls _ _ -> do
semif <- detectsemiflex c cls
let elim = detecteliminand cls
semifb = case (semif, elim) of
just copying val of . this should be changed
(_, _) -> Nothing
writeIORef c (cd {cdcont = Def narg cls elim semifb})
_ -> return ()
-- -------------------------------------------
class MetaliseOKH t where
metaliseOKH :: t -> IO t
instance MetaliseOKH t => MetaliseOKH (MM t a) where
metaliseOKH e = case e of
Meta m -> return $ Meta m
NotM e -> NotM <$> metaliseOKH e
instance MetaliseOKH t => MetaliseOKH (Abs t) where
metaliseOKH (Abs id b) = Abs id <$> metaliseOKH b
instance MetaliseOKH (Exp o) where
metaliseOKH e = case e of
App uid okh elr args ->
(\ m -> App uid m elr) <$> (Meta <$> initMeta) <*> metaliseOKH args
Lam hid b -> Lam hid <$> metaliseOKH b
Pi uid hid dep it ot ->
Pi uid hid dep <$> metaliseOKH it <*> metaliseOKH ot
Sort{} -> return e
AbsurdLambda{} -> return e
instance MetaliseOKH (ArgList o) where
metaliseOKH e = case e of
ALNil -> return ALNil
ALCons hid a as -> ALCons hid <$> metaliseOKH a <*> metaliseOKH as
ALProj eas idx hid as ->
(\ eas -> ALProj eas idx hid) <$> metaliseOKH eas <*> metaliseOKH as
ALConPar as -> ALConPar <$> metaliseOKH as
metaliseokh :: MExp o -> IO (MExp o)
metaliseokh = metaliseOKH
-- -------------------------------------------
class ExpandMetas t where
expandMetas :: t -> IO t
instance ExpandMetas t => ExpandMetas (MM t a) where
expandMetas t = case t of
NotM e -> NotM <$> expandMetas e
Meta m -> do
mb <- readIORef (mbind m)
case mb of
Nothing -> return $ Meta m
Just e -> NotM <$> expandMetas e
instance ExpandMetas t => ExpandMetas (Abs t) where
expandMetas (Abs id b) = Abs id <$> expandMetas b
instance ExpandMetas (Exp o) where
expandMetas t = case t of
App uid okh elr args -> App uid okh elr <$> expandMetas args
Lam hid b -> Lam hid <$> expandMetas b
Pi uid hid dep it ot ->
Pi uid hid dep <$> expandMetas it <*> expandMetas ot
Sort{} -> return t
AbsurdLambda{} -> return t
instance ExpandMetas (ArgList o) where
expandMetas e = case e of
ALNil -> return ALNil
ALCons hid a as -> ALCons hid <$> expandMetas a <*> expandMetas as
ALProj eas idx hid as ->
(\ a b -> ALProj a b hid) <$> expandMetas eas
<*> expandbind idx <*> expandMetas as
ALConPar as -> ALConPar <$> expandMetas as
-- ---------------------------------
addtrailingargs :: Clos (MArgList o) o -> ICArgList o -> ICArgList o
addtrailingargs newargs CALNil = CALConcat newargs CALNil
addtrailingargs newargs (CALConcat x xs) = CALConcat x (addtrailingargs newargs xs)
-- ---------------------------------
closify :: MExp o -> CExp o
closify e = TrBr [e] (Clos [] e)
sub :: MExp o -> CExp o -> CExp o
-- sub e (Clos [] x) = Clos [Sub e] x
sub e (TrBr trs (Clos (Skip : as) x)) = TrBr (e : trs) (Clos (Sub (Clos [] e) : as) x)
sub e ( Clos ( Weak n : as ) x ) = if n = = 1 then
as x
else
( Weak ( n - 1 ) : as ) x
Clos as x
else
Clos (Weak (n - 1) : as) x-}
sub _ _ = __IMPOSSIBLE__
subi :: MExp o -> ICExp o -> ICExp o
subi e (Clos (Skip : as) x) = Clos (Sub (Clos [] e) : as) x
subi _ _ = __IMPOSSIBLE__
weak :: Weakening t => Nat -> t -> t
weak 0 = id
weak n = weak' n
class Weakening t where
weak' :: Nat -> t -> t
instance Weakening a => Weakening (TrBr a o) where
weak' n (TrBr trs e) = TrBr trs (weak' n e)
instance Weakening (Clos a o) where
weak' n (Clos as x) = Clos (Weak n : as) x
instance Weakening (ICArgList o) where
weak' n e = case e of
CALNil -> CALNil
CALConcat a as -> CALConcat (weak' n a) (weak' n as)
instance Weakening (Elr o) where
weak' n = rename (n+)
-- | Substituting for a variable.
doclos :: [CAction o] -> Nat -> Either Nat (ICExp o)
doclos = f 0
where
-- ns is the number of weakenings
f ns [] i = Left (ns + i)
f ns (Weak n : xs) i = f (ns + n) xs i
f ns (Sub s : _ ) 0 = Right (weak ns s)
f ns (Skip : _ ) 0 = Left ns
f ns (Skip : xs) i = f (ns + 1) xs (i - 1)
f ns (Sub _ : xs) i = f ns xs (i - 1)
-- | FreeVars class and instances
freeVars :: FreeVars t => t -> Set.Set Nat
freeVars = freeVarsOffset 0
class FreeVars t where
freeVarsOffset :: Nat -> t -> Set.Set Nat
instance (FreeVars a, FreeVars b) => FreeVars (a, b) where
freeVarsOffset n (a, b) = Set.union (freeVarsOffset n a) (freeVarsOffset n b)
instance FreeVars t => FreeVars (MM t a) where
freeVarsOffset n e = freeVarsOffset n (rm __IMPOSSIBLE__ e)
instance FreeVars t => FreeVars (Abs t) where
freeVarsOffset n (Abs id e) = freeVarsOffset (n + 1) e
instance FreeVars (Elr o) where
freeVarsOffset n e = case e of
Var v -> Set.singleton (v - n)
Const{} -> Set.empty
instance FreeVars (Exp o) where
freeVarsOffset n e = case e of
App _ _ elr args -> freeVarsOffset n (elr, args)
Lam _ b -> freeVarsOffset n b
Pi _ _ _ it ot -> freeVarsOffset n (it, ot)
Sort{} -> Set.empty
AbsurdLambda{} -> Set.empty
instance FreeVars (ArgList o) where
freeVarsOffset n es = case es of
ALNil -> Set.empty
ALCons _ e es -> freeVarsOffset n (e, es)
ALConPar es -> freeVarsOffset n es
ALProj{} -> __IMPOSSIBLE__
| and instances
rename :: Renaming t => (Nat -> Nat) -> t -> t
rename = renameOffset 0
class Renaming t where
renameOffset :: Nat -> (Nat -> Nat) -> t -> t
instance (Renaming a, Renaming b) => Renaming (a, b) where
renameOffset j ren (a, b) = (renameOffset j ren a, renameOffset j ren b)
instance Renaming t => Renaming (MM t a) where
renameOffset j ren e = NotM $ renameOffset j ren (rm __IMPOSSIBLE__ e)
instance Renaming t => Renaming (Abs t) where
renameOffset j ren (Abs id e) = Abs id $ renameOffset (j + 1) ren e
instance Renaming (Elr o) where
renameOffset j ren e = case e of
Var v | v >= j -> Var (ren (v - j) + j)
_ -> e
instance Renaming (Exp o) where
renameOffset j ren e = case e of
App uid ok elr args -> uncurry (App uid ok) $ renameOffset j ren (elr, args)
Lam hid e -> Lam hid (renameOffset j ren e)
Pi a b c it ot -> uncurry (Pi a b c) $ renameOffset j ren (it, ot)
Sort{} -> e
AbsurdLambda{} -> e
instance Renaming (ArgList o) where
renameOffset j ren e = case e of
ALNil -> ALNil
ALCons hid a as -> uncurry (ALCons hid) $ renameOffset j ren (a, as)
ALConPar as -> ALConPar (renameOffset j ren as)
ALProj{} -> __IMPOSSIBLE__
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Auto/Syntax.hs | haskell | | Unique identifiers for variable occurrences in unification.
"_≡_"
"begin_"
"_≡⟨_⟩_"
"_∎"
"sym"
"cong"
| The concrete instance of the 'blk' parameter in 'Metavar'.
I.e., the information passed to the search control.
(to make cost of using module parameters correspond to that of hints).
^ Size of typing context in which meta was created.
^ Head normal form of type of meta.
^ True if iota steps performed when normalising target type
(used to put cost when traversing a definition
by construction instantiation).
True - semiflex
isdep
| Abstraction with maybe a name.
whether function is constant.
| Constant signatures.
^ For debug printing.
^ Type of constant.
^ Constant definition.
^ Free vars of the module where the constant is defined..
contains no metas
| Constant definitions.
maybe an index to elimand argument
constructors
projection functions (in case it is a record)
number of omitted args
^ Dot pattern.
TODO: projection patterns.
| PatProj (ConstRef o)
-- ^ Projection pattern.
| Head of application (elimination).
^ Unique identifier of the head.
^ This application has been type-checked.
^ Head.
^ Arguments.
^ Lambda with hiding information.
@False@ if non-dependent.
^ Absurd lambda with hiding information.
| "Maybe expression": Expression or reference to meta variable.
^ No more eliminations.
^ Application and tail.
Inserted to cover glitch of polymorphic constructor
Q: Why are there no projection eliminations?
| Lazy concatenation of argument lists under explicit substitutions.
| An expression @a@ in an explicit substitution @[CAction a]@.
| Entry of an explicit substitution.
An explicit substitution is a list of @CAction@s.
This is isomorphic to the usual presentation where
^ Instantation of variable.
^ For going under a binder, often called "Lift".
^ Shifting substitution (going to a larger context).
-------------------------------------------
disabled
-------------------------------------------
-------------------------------------------
---------------------------------
---------------------------------
sub e (Clos [] x) = Clos [Sub e] x
| Substituting for a variable.
ns is the number of weakenings
| FreeVars class and instances |
module Agda.Auto.Syntax where
import Data.IORef
import qualified Data.Set as Set
import Agda.Syntax.Common (Hiding)
import Agda.Auto.NarrowingSearch
import Agda.Utils.Impossible
type UId o = Metavar (Exp o) (RefInfo o)
data HintMode = HMNormal
| HMRecCall
data EqReasoningConsts o = EqReasoningConsts
:: ConstRef o
}
data EqReasoningState = EqRSNone | EqRSChain | EqRSPrf1 | EqRSPrf2 | EqRSPrf3
deriving (Eq, Show)
data RefInfo o
= RIEnv
{ rieHints :: [(ConstRef o, HintMode)]
, rieDefFreeVars :: Nat
^
, rieEqReasoningConsts :: Maybe (EqReasoningConsts o)
}
| RIMainInfo
{ riMainCxtLength :: Nat
, riMainType :: HNExp o
, riMainIota :: Bool
}
| RIUnifInfo [CAction o] (HNExp o)
meta environment ,
| RICopyInfo (ICExp o)
| RIInferredTypeUnknown
| RINotConstructor
| RIUsedVars [UId o] [Elr o]
| RIPickSubsvar
| RIEqRState EqReasoningState
noof proj functions
type MyPB o = PB (RefInfo o)
type MyMB a o = MB a (RefInfo o)
type Nat = Int
data MId = Id String
| NoId
Different from Agda , where there is also info
data Abs a = Abs MId a
data ConstDef o = ConstDef
{ cdname :: String
, cdorigin :: o
^ Reference to the Agda constant .
, cdtype :: MExp o
, cdcont :: DeclCont o
, cddeffreevars :: Nat
data DeclCont o
maybe index to elim arg if semiflex
| Postulate
type Clause o = ([Pat o], MExp o)
data Pat o
= PatConApp (ConstRef o) [Pat o]
| PatVar String
| PatExp
type ConstRef o = IORef (ConstDef o)
data Elr o
= Var Nat
| Const (ConstRef o)
deriving (Eq)
getVar :: Elr o -> Maybe Nat
getVar (Var n) = Just n
getVar Const{} = Nothing
getConst :: Elr o -> Maybe (ConstRef o)
getConst (Const c) = Just c
getConst Var{} = Nothing
data Sort
= Set Nat
| UnknownSort
| Type
| Agsy 's internal syntax .
data Exp o
= App
{ appUId :: Maybe (UId o)
, appOK :: OKHandle (RefInfo o)
, appHead :: Elr o
, appElims :: MArgList o
}
| Lam Hiding (Abs (MExp o))
| Pi (Maybe (UId o)) Hiding Bool (MExp o) (Abs (MExp o))
^ @True@ if possibly dependent ( var not known to not occur ) .
| Sort Sort
| AbsurdLambda Hiding
dontCare :: Exp o
dontCare = Sort UnknownSort
type MExp o = MM (Exp o) (RefInfo o)
data ArgList o
= ALNil
| ALCons Hiding (MExp o) (MArgList o)
| ALProj (MArgList o) (MM (ConstRef o) (RefInfo o)) Hiding (MArgList o)
^ proj pre args , projfcn idx , tail
| ALConPar (MArgList o)
^ Constructor parameter ( missing in Agda ) .
has monomorphic constructors .
applications coming from Agda
type MArgList o = MM (ArgList o) (RefInfo o)
data WithSeenUIds a o = WithSeenUIds
{ seenUIds :: [Maybe (UId o)]
, rawValue :: a
}
type HNExp o = WithSeenUIds (HNExp' o) o
data HNExp' o =
HNApp (Elr o) (ICArgList o)
| HNLam Hiding (Abs (ICExp o))
| HNPi Hiding Bool (ICExp o) (Abs (ICExp o))
| HNSort Sort
| Head - normal form of ' ICArgList ' . First entry is exposed .
data HNArgList o = HNALNil
| HNALCons Hiding (ICExp o) (ICArgList o)
| HNALConPar (ICArgList o)
data ICArgList o = CALNil
| CALConcat (Clos (MArgList o) o) (ICArgList o)
type ICExp o = Clos (MExp o) o
data Clos a o = Clos [CAction o] a
type CExp o = TrBr (ICExp o) o
data TrBr a o = TrBr [MExp o] a
and @Weak@ would be constructors of exp . substs .
data CAction o
= Sub (ICExp o)
| Skip
| Weak Nat
type Ctx o = [(MId, CExp o)]
type EE = IO
detecteliminand :: [Clause o] -> Maybe Nat
detecteliminand cls =
case map cleli cls of
[] -> Nothing
(i:is) -> if all (i ==) is then i else Nothing
where
cleli (pats, _) = pateli 0 pats
pateli i (PatConApp _ args : pats) = if all notcon (args ++ pats) then Just i else Nothing
pateli i (_ : pats) = pateli (i + 1) pats
pateli i [] = Nothing
notcon PatConApp{} = False
notcon _ = True
detectsemiflex :: ConstRef o -> [Clause o] -> IO Bool
categorizedecl :: ConstRef o -> IO ()
categorizedecl c = do
cd <- readIORef c
case cdcont cd of
Def narg cls _ _ -> do
semif <- detectsemiflex c cls
let elim = detecteliminand cls
semifb = case (semif, elim) of
just copying val of . this should be changed
(_, _) -> Nothing
writeIORef c (cd {cdcont = Def narg cls elim semifb})
_ -> return ()
class MetaliseOKH t where
metaliseOKH :: t -> IO t
instance MetaliseOKH t => MetaliseOKH (MM t a) where
metaliseOKH e = case e of
Meta m -> return $ Meta m
NotM e -> NotM <$> metaliseOKH e
instance MetaliseOKH t => MetaliseOKH (Abs t) where
metaliseOKH (Abs id b) = Abs id <$> metaliseOKH b
instance MetaliseOKH (Exp o) where
metaliseOKH e = case e of
App uid okh elr args ->
(\ m -> App uid m elr) <$> (Meta <$> initMeta) <*> metaliseOKH args
Lam hid b -> Lam hid <$> metaliseOKH b
Pi uid hid dep it ot ->
Pi uid hid dep <$> metaliseOKH it <*> metaliseOKH ot
Sort{} -> return e
AbsurdLambda{} -> return e
instance MetaliseOKH (ArgList o) where
metaliseOKH e = case e of
ALNil -> return ALNil
ALCons hid a as -> ALCons hid <$> metaliseOKH a <*> metaliseOKH as
ALProj eas idx hid as ->
(\ eas -> ALProj eas idx hid) <$> metaliseOKH eas <*> metaliseOKH as
ALConPar as -> ALConPar <$> metaliseOKH as
metaliseokh :: MExp o -> IO (MExp o)
metaliseokh = metaliseOKH
class ExpandMetas t where
expandMetas :: t -> IO t
instance ExpandMetas t => ExpandMetas (MM t a) where
expandMetas t = case t of
NotM e -> NotM <$> expandMetas e
Meta m -> do
mb <- readIORef (mbind m)
case mb of
Nothing -> return $ Meta m
Just e -> NotM <$> expandMetas e
instance ExpandMetas t => ExpandMetas (Abs t) where
expandMetas (Abs id b) = Abs id <$> expandMetas b
instance ExpandMetas (Exp o) where
expandMetas t = case t of
App uid okh elr args -> App uid okh elr <$> expandMetas args
Lam hid b -> Lam hid <$> expandMetas b
Pi uid hid dep it ot ->
Pi uid hid dep <$> expandMetas it <*> expandMetas ot
Sort{} -> return t
AbsurdLambda{} -> return t
instance ExpandMetas (ArgList o) where
expandMetas e = case e of
ALNil -> return ALNil
ALCons hid a as -> ALCons hid <$> expandMetas a <*> expandMetas as
ALProj eas idx hid as ->
(\ a b -> ALProj a b hid) <$> expandMetas eas
<*> expandbind idx <*> expandMetas as
ALConPar as -> ALConPar <$> expandMetas as
addtrailingargs :: Clos (MArgList o) o -> ICArgList o -> ICArgList o
addtrailingargs newargs CALNil = CALConcat newargs CALNil
addtrailingargs newargs (CALConcat x xs) = CALConcat x (addtrailingargs newargs xs)
closify :: MExp o -> CExp o
closify e = TrBr [e] (Clos [] e)
sub :: MExp o -> CExp o -> CExp o
sub e (TrBr trs (Clos (Skip : as) x)) = TrBr (e : trs) (Clos (Sub (Clos [] e) : as) x)
sub e ( Clos ( Weak n : as ) x ) = if n = = 1 then
as x
else
( Weak ( n - 1 ) : as ) x
Clos as x
else
Clos (Weak (n - 1) : as) x-}
sub _ _ = __IMPOSSIBLE__
subi :: MExp o -> ICExp o -> ICExp o
subi e (Clos (Skip : as) x) = Clos (Sub (Clos [] e) : as) x
subi _ _ = __IMPOSSIBLE__
weak :: Weakening t => Nat -> t -> t
weak 0 = id
weak n = weak' n
class Weakening t where
weak' :: Nat -> t -> t
instance Weakening a => Weakening (TrBr a o) where
weak' n (TrBr trs e) = TrBr trs (weak' n e)
instance Weakening (Clos a o) where
weak' n (Clos as x) = Clos (Weak n : as) x
instance Weakening (ICArgList o) where
weak' n e = case e of
CALNil -> CALNil
CALConcat a as -> CALConcat (weak' n a) (weak' n as)
instance Weakening (Elr o) where
weak' n = rename (n+)
doclos :: [CAction o] -> Nat -> Either Nat (ICExp o)
doclos = f 0
where
f ns [] i = Left (ns + i)
f ns (Weak n : xs) i = f (ns + n) xs i
f ns (Sub s : _ ) 0 = Right (weak ns s)
f ns (Skip : _ ) 0 = Left ns
f ns (Skip : xs) i = f (ns + 1) xs (i - 1)
f ns (Sub _ : xs) i = f ns xs (i - 1)
freeVars :: FreeVars t => t -> Set.Set Nat
freeVars = freeVarsOffset 0
class FreeVars t where
freeVarsOffset :: Nat -> t -> Set.Set Nat
instance (FreeVars a, FreeVars b) => FreeVars (a, b) where
freeVarsOffset n (a, b) = Set.union (freeVarsOffset n a) (freeVarsOffset n b)
instance FreeVars t => FreeVars (MM t a) where
freeVarsOffset n e = freeVarsOffset n (rm __IMPOSSIBLE__ e)
instance FreeVars t => FreeVars (Abs t) where
freeVarsOffset n (Abs id e) = freeVarsOffset (n + 1) e
instance FreeVars (Elr o) where
freeVarsOffset n e = case e of
Var v -> Set.singleton (v - n)
Const{} -> Set.empty
instance FreeVars (Exp o) where
freeVarsOffset n e = case e of
App _ _ elr args -> freeVarsOffset n (elr, args)
Lam _ b -> freeVarsOffset n b
Pi _ _ _ it ot -> freeVarsOffset n (it, ot)
Sort{} -> Set.empty
AbsurdLambda{} -> Set.empty
instance FreeVars (ArgList o) where
freeVarsOffset n es = case es of
ALNil -> Set.empty
ALCons _ e es -> freeVarsOffset n (e, es)
ALConPar es -> freeVarsOffset n es
ALProj{} -> __IMPOSSIBLE__
| and instances
rename :: Renaming t => (Nat -> Nat) -> t -> t
rename = renameOffset 0
class Renaming t where
renameOffset :: Nat -> (Nat -> Nat) -> t -> t
instance (Renaming a, Renaming b) => Renaming (a, b) where
renameOffset j ren (a, b) = (renameOffset j ren a, renameOffset j ren b)
instance Renaming t => Renaming (MM t a) where
renameOffset j ren e = NotM $ renameOffset j ren (rm __IMPOSSIBLE__ e)
instance Renaming t => Renaming (Abs t) where
renameOffset j ren (Abs id e) = Abs id $ renameOffset (j + 1) ren e
instance Renaming (Elr o) where
renameOffset j ren e = case e of
Var v | v >= j -> Var (ren (v - j) + j)
_ -> e
instance Renaming (Exp o) where
renameOffset j ren e = case e of
App uid ok elr args -> uncurry (App uid ok) $ renameOffset j ren (elr, args)
Lam hid e -> Lam hid (renameOffset j ren e)
Pi a b c it ot -> uncurry (Pi a b c) $ renameOffset j ren (it, ot)
Sort{} -> e
AbsurdLambda{} -> e
instance Renaming (ArgList o) where
renameOffset j ren e = case e of
ALNil -> ALNil
ALCons hid a as -> uncurry (ALCons hid) $ renameOffset j ren (a, as)
ALConPar as -> ALConPar (renameOffset j ren as)
ALProj{} -> __IMPOSSIBLE__
|
2e5a90b62c293bb65fc40d1c740c496c5f054a46d22ec9ea69e7e1d668f85ad4 | sunng87/slacker | common.clj | (ns slacker.common
(:require [trptcolin.versioneer.core :as ver]))
(def
^{:doc "Debug flag. This flag can be override by binding if you like to see some debug output."
:dynamic true}
*debug* false)
(def
^{:doc "Timeout for synchronouse call."
:dynamic true}
*timeout* 10000)
(def
^{:doc "Initial Kryo ObjectBuffer size (bytes)."
:dynamic true}
*ob-init* (* 1024 1))
(def
^{:doc "Maximum Kryo ObjectBuffer size (bytes)."
:dynamic true}
*ob-max* (* 1024 16))
(def
^{:doc "Max on-the-fly requests the client can have. Set to 0 to disable flow control."
:dynamic true}
*backlog* 5000)
(def
^{:doc "Request extension map, keyed by an integer as extension id."
:dynamic true}
*extensions* {})
(defmacro with-extensions
"Setting extension data for this invoke. Extension data is a map, keyed by an integer
extension id, the value can be any serializable data structure. Extension map will be
sent to remote server using same content type with the request body."
[ext-map & body]
`(binding [*extensions* ~ext-map] ~@body))
(def slacker-version
(ver/get-version "slacker" "slacker"))
| null | https://raw.githubusercontent.com/sunng87/slacker/60e5372782bed6fc58cb8ba55951516a6b971513/src/slacker/common.clj | clojure | (ns slacker.common
(:require [trptcolin.versioneer.core :as ver]))
(def
^{:doc "Debug flag. This flag can be override by binding if you like to see some debug output."
:dynamic true}
*debug* false)
(def
^{:doc "Timeout for synchronouse call."
:dynamic true}
*timeout* 10000)
(def
^{:doc "Initial Kryo ObjectBuffer size (bytes)."
:dynamic true}
*ob-init* (* 1024 1))
(def
^{:doc "Maximum Kryo ObjectBuffer size (bytes)."
:dynamic true}
*ob-max* (* 1024 16))
(def
^{:doc "Max on-the-fly requests the client can have. Set to 0 to disable flow control."
:dynamic true}
*backlog* 5000)
(def
^{:doc "Request extension map, keyed by an integer as extension id."
:dynamic true}
*extensions* {})
(defmacro with-extensions
"Setting extension data for this invoke. Extension data is a map, keyed by an integer
extension id, the value can be any serializable data structure. Extension map will be
sent to remote server using same content type with the request body."
[ext-map & body]
`(binding [*extensions* ~ext-map] ~@body))
(def slacker-version
(ver/get-version "slacker" "slacker"))
| |
34faf69fbae79b3f393a5ee7d0d9958e7cd2dd6524a0aa421883d6241eb0b8a6 | epgsql/epgsql | epgsql_cmd_batch.erl | %% @doc Execute multiple extended queries in a single network round-trip
%%
There are 2 kinds of interface :
%% <ol>
%% <li>To execute multiple queries, each with it's own `statement()'</li>
%% <li>To execute multiple queries, but by binding different parameters to the
%% same `statement()'</li>
%% </ol>
%% ```
%% > {Bind
< BindComplete
%% > Execute
< DataRow *
%% < CommandComplete}*
%% > Sync
%% < ReadyForQuery
%% '''
-module(epgsql_cmd_batch).
-behaviour(epgsql_command).
-export([init/1, execute/2, handle_message/4]).
-export_type([arguments/0, response/0]).
-include("epgsql.hrl").
-include("protocol.hrl").
-record(batch,
{batch :: [ [epgsql:bind_param()] ] | [{#statement{}, [epgsql:bind_param()]}],
statement :: #statement{} | undefined,
decoder :: epgsql_wire:row_decoder() | undefined}).
-type arguments() ::
{epgsql:statement(), [ [epgsql:bind_param()] ]} |
[{epgsql:statement(), [epgsql:bind_param()]}].
-type response() :: [{ok, Count :: non_neg_integer(), Rows :: [tuple()]}
| {ok, Count :: non_neg_integer()}
| {ok, Rows :: [tuple()]}
| {error, epgsql:query_error()}
].
-type state() :: #batch{}.
-spec init(arguments()) -> state().
init({#statement{} = Statement, Batch}) ->
#batch{statement = Statement,
batch = Batch};
init(Batch) when is_list(Batch) ->
#batch{batch = Batch}.
execute(Sock, #batch{batch = Batch, statement = undefined} = State) ->
Codec = epgsql_sock:get_codec(Sock),
Commands =
lists:foldr(
fun({Statement, Parameters}, Acc) ->
#statement{name = StatementName,
columns = Columns,
types = Types} = Statement,
BinFormats = epgsql_wire:encode_formats(Columns),
add_command(StatementName, Types, Parameters, BinFormats, Codec, Acc)
end,
[epgsql_wire:encode_sync()],
Batch),
{send_multi, Commands, Sock, State};
execute(Sock, #batch{batch = Batch,
statement = #statement{name = StatementName,
columns = Columns,
types = Types}} = State) ->
Codec = epgsql_sock:get_codec(Sock),
BinFormats = epgsql_wire:encode_formats(Columns),
%% TODO: build some kind of encoder and reuse it for each batch item
Commands =
lists:foldr(
fun(Parameters, Acc) ->
add_command(StatementName, Types, Parameters, BinFormats, Codec, Acc)
end,
[epgsql_wire:encode_sync()],
Batch),
{send_multi, Commands, Sock, State}.
add_command(StmtName, Types, Params, BinFormats, Codec, Acc) ->
TypedParameters = lists:zip(Types, Params),
BinParams = epgsql_wire:encode_parameters(TypedParameters, Codec),
[epgsql_wire:encode_bind("", StmtName, BinParams, BinFormats),
epgsql_wire:encode_execute("", 0) | Acc].
handle_message(?BIND_COMPLETE, <<>>, Sock, State) ->
Columns = current_cols(State),
Codec = epgsql_sock:get_codec(Sock),
Decoder = epgsql_wire:build_decoder(Columns, Codec),
{noaction, Sock, State#batch{decoder = Decoder}};
handle_message(?DATA_ROW, <<_Count:?int16, Bin/binary>>, Sock,
#batch{decoder = Decoder} = State) ->
Row = epgsql_wire:decode_data(Bin, Decoder),
{add_row, Row, Sock, State};
handle_message(?EMPTY_QUERY , _ , , _ State ) - >
Sock1 = epgsql_sock : add_result(Sock , { complete , empty } , { ok , [ ] , [ ] } ) ,
{ noaction , Sock1 } ;
handle_message(?COMMAND_COMPLETE, Bin, Sock,
#batch{batch = [_ | Batch]} = State) ->
Columns = current_cols(State),
Complete = epgsql_wire:decode_complete(Bin),
Rows = epgsql_sock:get_rows(Sock),
Result = case Complete of
{_, Count} when Columns == [] ->
{ok, Count};
{_, Count} ->
{ok, Count, Rows};
_ ->
{ok, Rows}
end,
{add_result, Result, {complete, Complete}, Sock, State#batch{batch = Batch}};
handle_message(?READY_FOR_QUERY, _Status, Sock, _State) ->
Results = epgsql_sock:get_results(Sock),
{finish, Results, done, Sock};
handle_message(?ERROR, Error, Sock, #batch{batch = [_ | Batch]} = State) ->
Result = {error, Error},
{add_result, Result, Result, Sock, State#batch{batch = Batch}};
handle_message(_, _, _, _) ->
unknown.
%% Helpers
current_cols(Batch) ->
#statement{columns = Columns} = current_stmt(Batch),
Columns.
current_stmt(#batch{batch = [{Stmt, _} | _], statement = undefined}) ->
Stmt;
current_stmt(#batch{statement = #statement{} = Stmt}) ->
Stmt.
| null | https://raw.githubusercontent.com/epgsql/epgsql/f811a09926892dbd1359afe44a9bfa8f6907b322/src/commands/epgsql_cmd_batch.erl | erlang | @doc Execute multiple extended queries in a single network round-trip
<ol>
<li>To execute multiple queries, each with it's own `statement()'</li>
<li>To execute multiple queries, but by binding different parameters to the
same `statement()'</li>
</ol>
```
> {Bind
> Execute
< CommandComplete}*
> Sync
< ReadyForQuery
'''
TODO: build some kind of encoder and reuse it for each batch item
Helpers | There are 2 kinds of interface :
< BindComplete
< DataRow *
-module(epgsql_cmd_batch).
-behaviour(epgsql_command).
-export([init/1, execute/2, handle_message/4]).
-export_type([arguments/0, response/0]).
-include("epgsql.hrl").
-include("protocol.hrl").
-record(batch,
{batch :: [ [epgsql:bind_param()] ] | [{#statement{}, [epgsql:bind_param()]}],
statement :: #statement{} | undefined,
decoder :: epgsql_wire:row_decoder() | undefined}).
-type arguments() ::
{epgsql:statement(), [ [epgsql:bind_param()] ]} |
[{epgsql:statement(), [epgsql:bind_param()]}].
-type response() :: [{ok, Count :: non_neg_integer(), Rows :: [tuple()]}
| {ok, Count :: non_neg_integer()}
| {ok, Rows :: [tuple()]}
| {error, epgsql:query_error()}
].
-type state() :: #batch{}.
-spec init(arguments()) -> state().
init({#statement{} = Statement, Batch}) ->
#batch{statement = Statement,
batch = Batch};
init(Batch) when is_list(Batch) ->
#batch{batch = Batch}.
execute(Sock, #batch{batch = Batch, statement = undefined} = State) ->
Codec = epgsql_sock:get_codec(Sock),
Commands =
lists:foldr(
fun({Statement, Parameters}, Acc) ->
#statement{name = StatementName,
columns = Columns,
types = Types} = Statement,
BinFormats = epgsql_wire:encode_formats(Columns),
add_command(StatementName, Types, Parameters, BinFormats, Codec, Acc)
end,
[epgsql_wire:encode_sync()],
Batch),
{send_multi, Commands, Sock, State};
execute(Sock, #batch{batch = Batch,
statement = #statement{name = StatementName,
columns = Columns,
types = Types}} = State) ->
Codec = epgsql_sock:get_codec(Sock),
BinFormats = epgsql_wire:encode_formats(Columns),
Commands =
lists:foldr(
fun(Parameters, Acc) ->
add_command(StatementName, Types, Parameters, BinFormats, Codec, Acc)
end,
[epgsql_wire:encode_sync()],
Batch),
{send_multi, Commands, Sock, State}.
add_command(StmtName, Types, Params, BinFormats, Codec, Acc) ->
TypedParameters = lists:zip(Types, Params),
BinParams = epgsql_wire:encode_parameters(TypedParameters, Codec),
[epgsql_wire:encode_bind("", StmtName, BinParams, BinFormats),
epgsql_wire:encode_execute("", 0) | Acc].
handle_message(?BIND_COMPLETE, <<>>, Sock, State) ->
Columns = current_cols(State),
Codec = epgsql_sock:get_codec(Sock),
Decoder = epgsql_wire:build_decoder(Columns, Codec),
{noaction, Sock, State#batch{decoder = Decoder}};
handle_message(?DATA_ROW, <<_Count:?int16, Bin/binary>>, Sock,
#batch{decoder = Decoder} = State) ->
Row = epgsql_wire:decode_data(Bin, Decoder),
{add_row, Row, Sock, State};
handle_message(?EMPTY_QUERY , _ , , _ State ) - >
Sock1 = epgsql_sock : add_result(Sock , { complete , empty } , { ok , [ ] , [ ] } ) ,
{ noaction , Sock1 } ;
handle_message(?COMMAND_COMPLETE, Bin, Sock,
#batch{batch = [_ | Batch]} = State) ->
Columns = current_cols(State),
Complete = epgsql_wire:decode_complete(Bin),
Rows = epgsql_sock:get_rows(Sock),
Result = case Complete of
{_, Count} when Columns == [] ->
{ok, Count};
{_, Count} ->
{ok, Count, Rows};
_ ->
{ok, Rows}
end,
{add_result, Result, {complete, Complete}, Sock, State#batch{batch = Batch}};
handle_message(?READY_FOR_QUERY, _Status, Sock, _State) ->
Results = epgsql_sock:get_results(Sock),
{finish, Results, done, Sock};
handle_message(?ERROR, Error, Sock, #batch{batch = [_ | Batch]} = State) ->
Result = {error, Error},
{add_result, Result, Result, Sock, State#batch{batch = Batch}};
handle_message(_, _, _, _) ->
unknown.
current_cols(Batch) ->
#statement{columns = Columns} = current_stmt(Batch),
Columns.
current_stmt(#batch{batch = [{Stmt, _} | _], statement = undefined}) ->
Stmt;
current_stmt(#batch{statement = #statement{} = Stmt}) ->
Stmt.
|
d45545e5b69c3d80dc1d32617c6c6148cf5421f339a714b6260bb2d1e066f298 | mihaiolteanu/zbucium | packages.lisp | (defpackage :zbucium
(:use :cl :plump :lquery :alexandria :generators
:bt :lastfm :youtube :lyrics)
(:import-from :drakma :http-request)
(:import-from :bordeaux-threads :make-thread)
(:import-from :bordeaux-threads :join-thread)
(:shadowing-import-from :yason :parse)
(:import-from :local-time :timestamp-to-unix)
(:import-from :local-time :now)
Functionality implemented by this library
play-song
play-artist
play-album
play-tag
play-user-songs
play-my-loved-songs
play-artist-similar
play-tag-similar
what-is-playing
what-is-playing-as-string
song-lyrics
love-song
unlove-song
next-song
stop
Reexported from lyrics
search-song
Reexported from youtube
pause
play/pause
replay
seek
percent-pos
time-pos
duration
switch-to-browser
turn-video-on
))
| null | https://raw.githubusercontent.com/mihaiolteanu/zbucium/5b0135f5c586088ae40183b0d7661fec5eb47791/packages.lisp | lisp | (defpackage :zbucium
(:use :cl :plump :lquery :alexandria :generators
:bt :lastfm :youtube :lyrics)
(:import-from :drakma :http-request)
(:import-from :bordeaux-threads :make-thread)
(:import-from :bordeaux-threads :join-thread)
(:shadowing-import-from :yason :parse)
(:import-from :local-time :timestamp-to-unix)
(:import-from :local-time :now)
Functionality implemented by this library
play-song
play-artist
play-album
play-tag
play-user-songs
play-my-loved-songs
play-artist-similar
play-tag-similar
what-is-playing
what-is-playing-as-string
song-lyrics
love-song
unlove-song
next-song
stop
Reexported from lyrics
search-song
Reexported from youtube
pause
play/pause
replay
seek
percent-pos
time-pos
duration
switch-to-browser
turn-video-on
))
| |
4714b9560e3c1bd643e838edf189e95c50794686ebd7011bb3328a54d7b46553 | janestreet/memtrace_viewer_with_deps | raw.ml | open Base
open Js_of_ocaml
open Gen_js_api
module Native_node : sig
type t = Dom_html.element Js.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
end = struct
type t = Dom_html.element Js.t
let t_of_js x = Stdlib.Obj.magic x
let t_to_js x = Stdlib.Obj.magic x
end
module Attrs : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val create : unit -> t
val set_property : t -> string -> Ojs.t -> unit
val set_attribute : t -> string -> Ojs.t -> unit
end = struct
type t = Ojs.t
let t_of_js x = x
let t_to_js x = x
let create () : t = Ojs.empty_obj ()
let set_property : t -> string -> t -> unit = fun t name value -> Ojs.set t name value
let set_attribute : t -> string -> t -> unit =
fun t name value ->
if phys_equal (Ojs.get t "attributes") (Ojs.variable "undefined")
then Ojs.set t "attributes" (Ojs.empty_obj ());
Ojs.set (Ojs.get t "attributes") name value
;;
end
module Node : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val node : string -> Attrs.t -> t list -> string option -> t
[@@js.new "VirtualDom.VNode"]
val text : string -> t [@@js.new "VirtualDom.VText"]
val svg : string -> Attrs.t -> t list -> string option -> t [@@js.new "VirtualDom.svg"]
val to_dom : t -> Native_node.t [@@js.global "VirtualDom.createElement"]
end =
[%js]
module Patch : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val create : previous:Node.t -> current:Node.t -> t [@@js.global "VirtualDom.diff"]
val apply : Native_node.t -> t -> Native_node.t [@@js.global "VirtualDom.patch"]
val is_empty : t -> bool
[@@js.custom
let is_empty =
let f =
Js.Unsafe.pure_js_expr
{js|
(function (patch) {
for (var key in patch) {
if (key !== 'a') return false
}
return true
})
|js}
in
fun (t : t) -> Js.Unsafe.fun_call f [| Js.Unsafe.inject t |] |> Js.to_bool
;;]
end =
[%js]
module Widget = struct
class type ['s, 'element] widget =
object
constraint 'element = #Dom_html.element Js.t
method type_ : Js.js_string Js.t Js.writeonly_prop
virtual - dom considers two widgets of being of the same " kind " if either
of the following holds :
1 . They both have a " name " attribute and their " i d " fields are equal .
( I think this is probably a bug in virtual - dom and have field an issue
on github : [ -Esch/virtual-dom/issues/380 ] )
2 . Their [ init ] methods are " = = = " equal . This is true when using virtual - dom
widgets in the usual style in Javascript , since the [ init ] method will be defined
on a prototype , but is not true in this binding as it is redefined for each
call to [ widget ] .
So , we go with option 1 and must have a trivial field called [ name ] .
of the following holds:
1. They both have a "name" attribute and their "id" fields are equal.
(I think this is probably a bug in virtual-dom and have field an issue
on github: [-Esch/virtual-dom/issues/380])
2. Their [init] methods are "===" equal. This is true when using virtual-dom
widgets in the usual style in Javascript, since the [init] method will be defined
on a prototype, but is not true in this binding as it is redefined for each
call to [widget].
So, we go with option 1 and must have a trivial field called [name].
*)
method name : unit Js.writeonly_prop
method id : ('s * 'element) Type_equal.Id.t Js.prop
method state : 's Js.prop
method info : Sexp.t Lazy.t option Js.prop
method destroy : ('element -> unit) Js.callback Js.writeonly_prop
method update :
(('other_state, 'other_element) widget Js.t -> 'element -> 'element) Js.callback
Js.writeonly_prop
method init : (unit -> 'element) Js.callback Js.writeonly_prop
end
We model JS level objects here so there is a lot of throwing away of type
information . We could possibly try to rediscover more of it . Or maybe we
should see if we can get rid Widget completely .
the unit type parameters here are not actually unit , but part of
the type info we have thrown away into our dance
with JS
information. We could possibly try to rediscover more of it. Or maybe we
should see if we can get rid Widget completely.
the unit type parameters here are not actually unit, but part of
the type info we have thrown away into our dance
with JS *)
type t = Node.t
(* here is how we throw away type information. Our good old friend Obj.magic,
but constrained a little bit *)
external ojs_of_js : (_, _) widget Js.t -> Ojs.t = "%identity"
let create
(type s)
?info
?(destroy : s -> 'element -> unit = fun _ _ -> ())
?(update : s -> 'element -> s * 'element = fun s elt -> s, elt)
~(id : (s * 'element) Type_equal.Id.t)
~(init : unit -> s * 'element)
()
=
let obj : (s, _) widget Js.t = Js.Unsafe.obj [||] in
obj##.type_ := Js.string "Widget";
obj##.name := ();
obj##.id := id;
obj##.info := info;
obj##.init
:= Js.wrap_callback (fun () ->
let s0, dom_node = init () in
obj##.state := s0;
dom_node);
obj##.update
:= Js.wrap_callback (fun prev dom_node ->
(* The [update] method of [obj] is only called by virtual-dom after it has checked
that the [id]s of [prev] and [obj] are "===" equal. Thus [same_witness_exn] will
never raise.
*)
match Type_equal.Id.same_witness_exn prev##.id id with
| Type_equal.T ->
let state', dom_node' = update prev##.state dom_node in
obj##.state := state';
dom_node');
obj##.destroy := Js.wrap_callback (fun dom_node -> destroy obj##.state dom_node);
Node.t_of_js (ojs_of_js obj)
;;
end
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/virtual_dom/src/raw.ml | ocaml | here is how we throw away type information. Our good old friend Obj.magic,
but constrained a little bit
The [update] method of [obj] is only called by virtual-dom after it has checked
that the [id]s of [prev] and [obj] are "===" equal. Thus [same_witness_exn] will
never raise.
| open Base
open Js_of_ocaml
open Gen_js_api
module Native_node : sig
type t = Dom_html.element Js.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
end = struct
type t = Dom_html.element Js.t
let t_of_js x = Stdlib.Obj.magic x
let t_to_js x = Stdlib.Obj.magic x
end
module Attrs : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val create : unit -> t
val set_property : t -> string -> Ojs.t -> unit
val set_attribute : t -> string -> Ojs.t -> unit
end = struct
type t = Ojs.t
let t_of_js x = x
let t_to_js x = x
let create () : t = Ojs.empty_obj ()
let set_property : t -> string -> t -> unit = fun t name value -> Ojs.set t name value
let set_attribute : t -> string -> t -> unit =
fun t name value ->
if phys_equal (Ojs.get t "attributes") (Ojs.variable "undefined")
then Ojs.set t "attributes" (Ojs.empty_obj ());
Ojs.set (Ojs.get t "attributes") name value
;;
end
module Node : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val node : string -> Attrs.t -> t list -> string option -> t
[@@js.new "VirtualDom.VNode"]
val text : string -> t [@@js.new "VirtualDom.VText"]
val svg : string -> Attrs.t -> t list -> string option -> t [@@js.new "VirtualDom.svg"]
val to_dom : t -> Native_node.t [@@js.global "VirtualDom.createElement"]
end =
[%js]
module Patch : sig
type t = private Ojs.t
val t_of_js : Ojs.t -> t
val t_to_js : t -> Ojs.t
val create : previous:Node.t -> current:Node.t -> t [@@js.global "VirtualDom.diff"]
val apply : Native_node.t -> t -> Native_node.t [@@js.global "VirtualDom.patch"]
val is_empty : t -> bool
[@@js.custom
let is_empty =
let f =
Js.Unsafe.pure_js_expr
{js|
(function (patch) {
for (var key in patch) {
if (key !== 'a') return false
}
return true
})
|js}
in
fun (t : t) -> Js.Unsafe.fun_call f [| Js.Unsafe.inject t |] |> Js.to_bool
;;]
end =
[%js]
module Widget = struct
class type ['s, 'element] widget =
object
constraint 'element = #Dom_html.element Js.t
method type_ : Js.js_string Js.t Js.writeonly_prop
virtual - dom considers two widgets of being of the same " kind " if either
of the following holds :
1 . They both have a " name " attribute and their " i d " fields are equal .
( I think this is probably a bug in virtual - dom and have field an issue
on github : [ -Esch/virtual-dom/issues/380 ] )
2 . Their [ init ] methods are " = = = " equal . This is true when using virtual - dom
widgets in the usual style in Javascript , since the [ init ] method will be defined
on a prototype , but is not true in this binding as it is redefined for each
call to [ widget ] .
So , we go with option 1 and must have a trivial field called [ name ] .
of the following holds:
1. They both have a "name" attribute and their "id" fields are equal.
(I think this is probably a bug in virtual-dom and have field an issue
on github: [-Esch/virtual-dom/issues/380])
2. Their [init] methods are "===" equal. This is true when using virtual-dom
widgets in the usual style in Javascript, since the [init] method will be defined
on a prototype, but is not true in this binding as it is redefined for each
call to [widget].
So, we go with option 1 and must have a trivial field called [name].
*)
method name : unit Js.writeonly_prop
method id : ('s * 'element) Type_equal.Id.t Js.prop
method state : 's Js.prop
method info : Sexp.t Lazy.t option Js.prop
method destroy : ('element -> unit) Js.callback Js.writeonly_prop
method update :
(('other_state, 'other_element) widget Js.t -> 'element -> 'element) Js.callback
Js.writeonly_prop
method init : (unit -> 'element) Js.callback Js.writeonly_prop
end
We model JS level objects here so there is a lot of throwing away of type
information . We could possibly try to rediscover more of it . Or maybe we
should see if we can get rid Widget completely .
the unit type parameters here are not actually unit , but part of
the type info we have thrown away into our dance
with JS
information. We could possibly try to rediscover more of it. Or maybe we
should see if we can get rid Widget completely.
the unit type parameters here are not actually unit, but part of
the type info we have thrown away into our dance
with JS *)
type t = Node.t
external ojs_of_js : (_, _) widget Js.t -> Ojs.t = "%identity"
let create
(type s)
?info
?(destroy : s -> 'element -> unit = fun _ _ -> ())
?(update : s -> 'element -> s * 'element = fun s elt -> s, elt)
~(id : (s * 'element) Type_equal.Id.t)
~(init : unit -> s * 'element)
()
=
let obj : (s, _) widget Js.t = Js.Unsafe.obj [||] in
obj##.type_ := Js.string "Widget";
obj##.name := ();
obj##.id := id;
obj##.info := info;
obj##.init
:= Js.wrap_callback (fun () ->
let s0, dom_node = init () in
obj##.state := s0;
dom_node);
obj##.update
:= Js.wrap_callback (fun prev dom_node ->
match Type_equal.Id.same_witness_exn prev##.id id with
| Type_equal.T ->
let state', dom_node' = update prev##.state dom_node in
obj##.state := state';
dom_node');
obj##.destroy := Js.wrap_callback (fun dom_node -> destroy obj##.state dom_node);
Node.t_of_js (ojs_of_js obj)
;;
end
|
6dcef8b3e97ebe5adcac1954dd90c94a3a687e8e1be67d79eec83b2da0da9e1a | filipesilva/roam-to-csv | main.cljc | (ns roam-to-csv.main
(:require [roam-to-csv.compat :as compat]
[roam-to-csv.athens :as athens]
[roam-to-csv.roam :as roam]
[clojure.string :as str]
[clojure.edn :as edn]
[clojure.tools.cli :as cli]
[clojure.pprint :as pprint]
[datascript.core :as d]
[tick.alpha.api :as t])
;; Needed for standalone jar to invoke with java
#?(:clj (:gen-class)))
(defn read-db [edn-string]
(edn/read-string {:readers d/data-readers} edn-string))
(defn read-query [edn-string]
(edn/read-string edn-string))
;; TODO:
;; --query-file
;; --query-params
(def cli-options
[["-e" "--extra" "Include extra information: user, edit, open, path, refs."]
["-q" "--query QUERY" "Use a custom Datalog query to create the CSV."
:parse-fn read-query]
["-p" "--pretty-print" "Pretty print the EDN export only."]
["-c" "--convert FORMAT" "Convert an input csv to another format [athens.transit roam.json]"]
["-h" "--help" "Show this message."]])
(defn print-help [summary]
(println "Convert a Roam Research EDN export into CSV format.")
(println "Given ./backup.edn, creates ./backup.csv with pages and blocks.")
(println)
(println "Usage:")
(println " roam-to-csv ./backup.edn")
(println)
(println "Options:")
;; Tools.cli provides a :summary key that can be used for printing:
(println summary))
(defn format-ms [ms]
(-> ms (t/new-duration :millis) t/instant str))
(defn page?
[{:keys [block/uid node/title]}]
(and uid title))
(defn page-v
[{:keys [block/uid node/title create/time]}]
[uid title nil nil nil (-> time (or 0) format-ms)])
(defn block?
[{:block/keys [uid string order _children]}]
(and uid string order (first _children)))
(defn block-v
[{:block/keys [uid string order _children] :keys [:create/time]}]
[uid nil (-> _children first :block/uid) string order (-> time (or 0) format-ms)])
(defn uid->refs
[db uid]
(->> [:block/uid uid]
(d/pull db '[{:block/refs [:block/uid]}])
:block/refs
(map :block/uid)))
(defn collect-uids
[m]
(loop [{:keys [block/uid block/_children]} m
uids []]
(if uid
(recur (first _children) (conj uids uid))
uids)))
(defn uid->path
[db uid]
(->> [:block/uid uid]
(d/pull db '[:block/uid {:block/_children ...}])
collect-uids
reverse
vec))
(defn add-path-and-refs
[db [uid :as v]]
(into v [(uid->path db uid)
(uid->refs db uid)]))
(defn vec->csv-str
[v]
(when (seq v)
(str/join "," v)))
(defn add-extra-fields
[db [uid title :as v]]
(let [e (d/entity db [:block/uid uid])]
(into v [(-> e :create/user :user/uid (or ""))
(-> e :create/user :user/display-name (or ""))
(-> e :edit/time (or 0) format-ms)
(-> e :edit/user :user/uid (or ""))
(-> e :edit/user :user/display-name (or ""))
(when-not title (if (:block/open e) 1 0))
(-> db (uid->path uid) vec->csv-str)
(-> db (uid->refs uid) vec->csv-str)])))
(defn query->header
"Extract the :find bindings as strings, stripped of the initial ? if any."
[query]
(->> (partition-by keyword? query)
second
(map str)
(map #(if (str/starts-with? % "?") (subs % 1) %))
vec))
(def simple-headers ["uid" "title" "parent" "string" "order" "create-time"])
(def extra-headers ["uid" "title" "parent" "string" "order"
"create-time" "create-user-uid" "create-user-display-name"
"edit-time" "edit-user-uid" "edit-user-display-name"
"open" "path" "refs"])
(defn entity-xf
[db attr & xfs]
(sequence
(apply comp (map first) (map (partial d/entity db)) xfs)
(d/datoms db :avet attr)))
(defmulti roam-db->csv-table
"Return a CSV table vector from q over db."
(fn [q _db]
q))
(defmethod roam-db->csv-table
:simple
[_q db]
(vec (concat [simple-headers]
(entity-xf db :node/title (filter page?) (map page-v))
(entity-xf db :block/uid (filter block?) (map block-v)))))
(defmethod roam-db->csv-table
:extra
[_q db]
(let [add-extra-fields' (partial add-extra-fields db)]
(vec (concat [extra-headers]
(entity-xf db :node/title (filter page?) (map page-v) (map add-extra-fields'))
(entity-xf db :block/uid (filter block?) (map block-v) (map add-extra-fields'))))))
(defmethod roam-db->csv-table
:default
[q db]
(let [res (d/q q db)
header (query->header q)]
(into [header] (map vec res))))
(defn csv-row->map
[header row]
(zipmap header row))
(defn csv-data
[csv-str]
(let [csv (compat/read-csv csv-str)
header (first csv)
data (rest csv)
min-headers (->> simple-headers (take 5) vec)]
(if-not (every? (set header) min-headers)
(throw (ex-info (str "Unsupported header format for conversion, header must contain at least" min-headers)
{:header header}))
(map (partial csv-row->map header) data))))
(defmulti convert-csv
(fn [type _edn-string]
type))
(defmethod convert-csv
"athens.transit"
[_format csv-str]
(let [data (csv-data csv-str)
conn (athens/create-conn)]
(doseq [{:strs [uid title parent string order]} data]
(if (empty? title)
(athens/add-block! conn uid parent string order)
(athens/add-page! conn uid title)))
(athens/conn-to-str conn)))
(defmethod convert-csv "roam.json"
[_format csv-str]
(let [data (csv-data csv-str)
conn (roam/create-conn)]
(doseq [{:strs [uid title parent string order create-time create-user-uid edit-time edit-user-uid]} data]
(let [order (compat/parse-int order)]
(when (seq uid)
(if (empty? title)
(roam/add-block! conn uid parent string order create-time create-user-uid edit-time edit-user-uid)
(roam/add-page! conn uid title create-time create-user-uid edit-time edit-user-uid)))))
(roam/conn-to-json conn)))
(defmethod convert-csv :default
[format _csv-str]
(throw (ex-info "Unknown convert format" {:format format})))
(defn format-ext
[format]
(case format
"athens.transit" ".transit"
"roam.json" ".json"
(throw (ex-info "Unsupported format" {:format format}))))
(defn slurp-xform-spit
([input-filename new-ext xform]
(let [filename-without-ext (subs input-filename 0 (str/last-index-of input-filename "."))
output-filename (str filename-without-ext new-ext)]
(->> input-filename
compat/slurp
xform
(compat/spit output-filename)))))
(defn roam-to-csv
[input-filename options]
(let [{:keys [pretty-print query extra convert]} options]
(cond
(str/blank? input-filename)
(println "Invalid filename, it must be non-empty")
pretty-print
(slurp-xform-spit input-filename ".pp.edn" (comp pprint/pprint read-db))
convert
(slurp-xform-spit input-filename (format-ext convert) (partial convert-csv convert))
:else
(slurp-xform-spit input-filename ".csv" (comp
compat/csv-str
(partial roam-db->csv-table
(or query
(when extra :extra)
:simple))
read-db)))))
(defn -main [& args]
(let [{:keys [options arguments summary]} (cli/parse-opts args cli-options)
{:keys [help]} options
input-filename (first arguments)]
(cond
help
(print-help summary)
:else
(roam-to-csv input-filename options))))
#?(:cljs
(def ^:export node-exports
#js {:roamToCsv (fn node-roam-to-csv
[input-filename options]
(roam-to-csv input-filename (js->clj options :keywordize-keys true)))
:main -main}))
(comment
;; Read the file as a Datascript database
(def db (-> "./test-goldens/simple/backup.edn" compat/slurp read-db))
db
;; Simple and extra query
(roam-db->csv-table :simple db)
(roam-db->csv-table :extra db)
;; Custom query for uids+blocks
(roam-db->csv-table
'[:find ?uid ?string ?p
:where
[?b :block/uid ?uid]
[?b :block/string ?string]
[?p :block/children ?b]]
db)
Custom query for all attrs
(roam-db->csv-table
'[:find (distinct ?attr)
:where
[?e ?attr]]
db)
)
| null | https://raw.githubusercontent.com/filipesilva/roam-to-csv/4fead192df5ce9baff5003e0135d46c4b8fec638/src/roam_to_csv/main.cljc | clojure | Needed for standalone jar to invoke with java
TODO:
--query-file
--query-params
Tools.cli provides a :summary key that can be used for printing:
Read the file as a Datascript database
Simple and extra query
Custom query for uids+blocks | (ns roam-to-csv.main
(:require [roam-to-csv.compat :as compat]
[roam-to-csv.athens :as athens]
[roam-to-csv.roam :as roam]
[clojure.string :as str]
[clojure.edn :as edn]
[clojure.tools.cli :as cli]
[clojure.pprint :as pprint]
[datascript.core :as d]
[tick.alpha.api :as t])
#?(:clj (:gen-class)))
(defn read-db [edn-string]
(edn/read-string {:readers d/data-readers} edn-string))
(defn read-query [edn-string]
(edn/read-string edn-string))
(def cli-options
[["-e" "--extra" "Include extra information: user, edit, open, path, refs."]
["-q" "--query QUERY" "Use a custom Datalog query to create the CSV."
:parse-fn read-query]
["-p" "--pretty-print" "Pretty print the EDN export only."]
["-c" "--convert FORMAT" "Convert an input csv to another format [athens.transit roam.json]"]
["-h" "--help" "Show this message."]])
(defn print-help [summary]
(println "Convert a Roam Research EDN export into CSV format.")
(println "Given ./backup.edn, creates ./backup.csv with pages and blocks.")
(println)
(println "Usage:")
(println " roam-to-csv ./backup.edn")
(println)
(println "Options:")
(println summary))
(defn format-ms [ms]
(-> ms (t/new-duration :millis) t/instant str))
(defn page?
[{:keys [block/uid node/title]}]
(and uid title))
(defn page-v
[{:keys [block/uid node/title create/time]}]
[uid title nil nil nil (-> time (or 0) format-ms)])
(defn block?
[{:block/keys [uid string order _children]}]
(and uid string order (first _children)))
(defn block-v
[{:block/keys [uid string order _children] :keys [:create/time]}]
[uid nil (-> _children first :block/uid) string order (-> time (or 0) format-ms)])
(defn uid->refs
[db uid]
(->> [:block/uid uid]
(d/pull db '[{:block/refs [:block/uid]}])
:block/refs
(map :block/uid)))
(defn collect-uids
[m]
(loop [{:keys [block/uid block/_children]} m
uids []]
(if uid
(recur (first _children) (conj uids uid))
uids)))
(defn uid->path
[db uid]
(->> [:block/uid uid]
(d/pull db '[:block/uid {:block/_children ...}])
collect-uids
reverse
vec))
(defn add-path-and-refs
[db [uid :as v]]
(into v [(uid->path db uid)
(uid->refs db uid)]))
(defn vec->csv-str
[v]
(when (seq v)
(str/join "," v)))
(defn add-extra-fields
[db [uid title :as v]]
(let [e (d/entity db [:block/uid uid])]
(into v [(-> e :create/user :user/uid (or ""))
(-> e :create/user :user/display-name (or ""))
(-> e :edit/time (or 0) format-ms)
(-> e :edit/user :user/uid (or ""))
(-> e :edit/user :user/display-name (or ""))
(when-not title (if (:block/open e) 1 0))
(-> db (uid->path uid) vec->csv-str)
(-> db (uid->refs uid) vec->csv-str)])))
(defn query->header
"Extract the :find bindings as strings, stripped of the initial ? if any."
[query]
(->> (partition-by keyword? query)
second
(map str)
(map #(if (str/starts-with? % "?") (subs % 1) %))
vec))
(def simple-headers ["uid" "title" "parent" "string" "order" "create-time"])
(def extra-headers ["uid" "title" "parent" "string" "order"
"create-time" "create-user-uid" "create-user-display-name"
"edit-time" "edit-user-uid" "edit-user-display-name"
"open" "path" "refs"])
(defn entity-xf
[db attr & xfs]
(sequence
(apply comp (map first) (map (partial d/entity db)) xfs)
(d/datoms db :avet attr)))
(defmulti roam-db->csv-table
"Return a CSV table vector from q over db."
(fn [q _db]
q))
(defmethod roam-db->csv-table
:simple
[_q db]
(vec (concat [simple-headers]
(entity-xf db :node/title (filter page?) (map page-v))
(entity-xf db :block/uid (filter block?) (map block-v)))))
(defmethod roam-db->csv-table
:extra
[_q db]
(let [add-extra-fields' (partial add-extra-fields db)]
(vec (concat [extra-headers]
(entity-xf db :node/title (filter page?) (map page-v) (map add-extra-fields'))
(entity-xf db :block/uid (filter block?) (map block-v) (map add-extra-fields'))))))
(defmethod roam-db->csv-table
:default
[q db]
(let [res (d/q q db)
header (query->header q)]
(into [header] (map vec res))))
(defn csv-row->map
[header row]
(zipmap header row))
(defn csv-data
[csv-str]
(let [csv (compat/read-csv csv-str)
header (first csv)
data (rest csv)
min-headers (->> simple-headers (take 5) vec)]
(if-not (every? (set header) min-headers)
(throw (ex-info (str "Unsupported header format for conversion, header must contain at least" min-headers)
{:header header}))
(map (partial csv-row->map header) data))))
(defmulti convert-csv
(fn [type _edn-string]
type))
(defmethod convert-csv
"athens.transit"
[_format csv-str]
(let [data (csv-data csv-str)
conn (athens/create-conn)]
(doseq [{:strs [uid title parent string order]} data]
(if (empty? title)
(athens/add-block! conn uid parent string order)
(athens/add-page! conn uid title)))
(athens/conn-to-str conn)))
(defmethod convert-csv "roam.json"
[_format csv-str]
(let [data (csv-data csv-str)
conn (roam/create-conn)]
(doseq [{:strs [uid title parent string order create-time create-user-uid edit-time edit-user-uid]} data]
(let [order (compat/parse-int order)]
(when (seq uid)
(if (empty? title)
(roam/add-block! conn uid parent string order create-time create-user-uid edit-time edit-user-uid)
(roam/add-page! conn uid title create-time create-user-uid edit-time edit-user-uid)))))
(roam/conn-to-json conn)))
(defmethod convert-csv :default
[format _csv-str]
(throw (ex-info "Unknown convert format" {:format format})))
(defn format-ext
[format]
(case format
"athens.transit" ".transit"
"roam.json" ".json"
(throw (ex-info "Unsupported format" {:format format}))))
(defn slurp-xform-spit
([input-filename new-ext xform]
(let [filename-without-ext (subs input-filename 0 (str/last-index-of input-filename "."))
output-filename (str filename-without-ext new-ext)]
(->> input-filename
compat/slurp
xform
(compat/spit output-filename)))))
(defn roam-to-csv
[input-filename options]
(let [{:keys [pretty-print query extra convert]} options]
(cond
(str/blank? input-filename)
(println "Invalid filename, it must be non-empty")
pretty-print
(slurp-xform-spit input-filename ".pp.edn" (comp pprint/pprint read-db))
convert
(slurp-xform-spit input-filename (format-ext convert) (partial convert-csv convert))
:else
(slurp-xform-spit input-filename ".csv" (comp
compat/csv-str
(partial roam-db->csv-table
(or query
(when extra :extra)
:simple))
read-db)))))
(defn -main [& args]
(let [{:keys [options arguments summary]} (cli/parse-opts args cli-options)
{:keys [help]} options
input-filename (first arguments)]
(cond
help
(print-help summary)
:else
(roam-to-csv input-filename options))))
#?(:cljs
(def ^:export node-exports
#js {:roamToCsv (fn node-roam-to-csv
[input-filename options]
(roam-to-csv input-filename (js->clj options :keywordize-keys true)))
:main -main}))
(comment
(def db (-> "./test-goldens/simple/backup.edn" compat/slurp read-db))
db
(roam-db->csv-table :simple db)
(roam-db->csv-table :extra db)
(roam-db->csv-table
'[:find ?uid ?string ?p
:where
[?b :block/uid ?uid]
[?b :block/string ?string]
[?p :block/children ?b]]
db)
Custom query for all attrs
(roam-db->csv-table
'[:find (distinct ?attr)
:where
[?e ?attr]]
db)
)
|
5bcdc1761b3939008ba2b4f26f7fce35cd27ebf81395e8ae1473e30ce94ac53f | yminer/libml | initVisitor.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version . This
program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details . You should have
received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 ,
USA .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have
received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
The initVisitor virtual class
@author
@author
@since 06/08/2003
The initVisitor virtual class
@author Matthieu Lagacherie
@author Olivier Ricordeau
@since 06/08/2003
*)
open DefaultVisitor
(**
The abstract initialisation visitor.
Instances of derived classes are supposed to initialize various kinds of
neural networks.
*)
class virtual ['a] initVisitor =
object
inherit ['a] defaultVisitor
*
The generic visit method .
//FIXME : add instanciation of an inheriting visitor depending on the
nn 's dynamic type .
The generic visit method.
//FIXME: add instanciation of an inheriting visitor depending on the
nn's dynamic type.
*)
method visit (nn : 'a) =
()
end
| null | https://raw.githubusercontent.com/yminer/libml/1475dd87c2c16983366fab62124e8bbfbbf2161b/src/nn/init/initVisitor.ml | ocaml | *
The abstract initialisation visitor.
Instances of derived classes are supposed to initialize various kinds of
neural networks.
| * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version . This
program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details . You should have
received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 ,
USA .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have
received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
The initVisitor virtual class
@author
@author
@since 06/08/2003
The initVisitor virtual class
@author Matthieu Lagacherie
@author Olivier Ricordeau
@since 06/08/2003
*)
open DefaultVisitor
class virtual ['a] initVisitor =
object
inherit ['a] defaultVisitor
*
The generic visit method .
//FIXME : add instanciation of an inheriting visitor depending on the
nn 's dynamic type .
The generic visit method.
//FIXME: add instanciation of an inheriting visitor depending on the
nn's dynamic type.
*)
method visit (nn : 'a) =
()
end
|
8c0f6e205f57c34f0cfc2d62b78901eee312455b80fc4b3c6b1f29337e989b63 | oakes/Nightcode | start.clj | (ns {{name}}.start
(:require [{{name}}.{{core-name}} :as c]
[{{name}}.music :as m]
[play-cljc.gl.core :as pc])
(:import [org.lwjgl.glfw GLFW Callbacks
GLFWCursorPosCallbackI GLFWKeyCallbackI GLFWMouseButtonCallbackI
GLFWCharCallbackI GLFWFramebufferSizeCallbackI]
[org.lwjgl.opengl GL GL41]
[org.lwjgl.system MemoryUtil]
[javax.sound.sampled AudioSystem Clip])
(:gen-class))
(defn play-music! []
(doto (AudioSystem/getClip)
(.open (AudioSystem/getAudioInputStream (m/build-for-clj)))
(.loop Clip/LOOP_CONTINUOUSLY)
(.start)))
(defn mousecode->keyword [mousecode]
(condp = mousecode
GLFW/GLFW_MOUSE_BUTTON_LEFT :left
GLFW/GLFW_MOUSE_BUTTON_RIGHT :right
nil))
(defn on-mouse-move! [window xpos ypos]
(let [*fb-width (MemoryUtil/memAllocInt 1)
*fb-height (MemoryUtil/memAllocInt 1)
*window-width (MemoryUtil/memAllocInt 1)
*window-height (MemoryUtil/memAllocInt 1)
_ (GLFW/glfwGetFramebufferSize window *fb-width *fb-height)
_ (GLFW/glfwGetWindowSize window *window-width *window-height)
fb-width (.get *fb-width)
fb-height (.get *fb-height)
window-width (.get *window-width)
window-height (.get *window-height)
width-ratio (/ fb-width window-width)
height-ratio (/ fb-height window-height)
x (* xpos width-ratio)
y (* ypos height-ratio)]
(MemoryUtil/memFree *fb-width)
(MemoryUtil/memFree *fb-height)
(MemoryUtil/memFree *window-width)
(MemoryUtil/memFree *window-height)
(swap! c/*state assoc :mouse-x x :mouse-y y)))
(defn on-mouse-click! [window button action mods]
(swap! c/*state assoc :mouse-button (when (= action GLFW/GLFW_PRESS)
(mousecode->keyword button))))
(defn keycode->keyword [keycode]
(condp = keycode
GLFW/GLFW_KEY_LEFT :left
GLFW/GLFW_KEY_RIGHT :right
GLFW/GLFW_KEY_UP :up
GLFW/GLFW_KEY_DOWN :down
nil))
(defn on-key! [window keycode scancode action mods]
(when-let [k (keycode->keyword keycode)]
(condp = action
GLFW/GLFW_PRESS (swap! c/*state update :pressed-keys conj k)
GLFW/GLFW_RELEASE (swap! c/*state update :pressed-keys disj k)
nil)))
(defn on-char! [window codepoint])
(defn on-resize! [window width height])
(defprotocol Events
(on-mouse-move [this xpos ypos])
(on-mouse-click [this button action mods])
(on-key [this keycode scancode action mods])
(on-char [this codepoint])
(on-resize [this width height])
(on-tick [this game]))
(defrecord Window [handle])
(extend-type Window
Events
(on-mouse-move [{:keys [handle]} xpos ypos]
(on-mouse-move! handle xpos ypos))
(on-mouse-click [{:keys [handle]} button action mods]
(on-mouse-click! handle button action mods))
(on-key [{:keys [handle]} keycode scancode action mods]
(on-key! handle keycode scancode action mods))
(on-char [{:keys [handle]} codepoint]
(on-char! handle codepoint))
(on-resize [{:keys [handle]} width height]
(on-resize! handle width height))
(on-tick [this game]
(c/tick game)))
(defn listen-for-events [{:keys [handle] :as window}]
(doto handle
(GLFW/glfwSetCursorPosCallback
(reify GLFWCursorPosCallbackI
(invoke [this _ xpos ypos]
(on-mouse-move window xpos ypos))))
(GLFW/glfwSetMouseButtonCallback
(reify GLFWMouseButtonCallbackI
(invoke [this _ button action mods]
(on-mouse-click window button action mods))))
(GLFW/glfwSetKeyCallback
(reify GLFWKeyCallbackI
(invoke [this _ keycode scancode action mods]
(on-key window keycode scancode action mods))))
(GLFW/glfwSetCharCallback
(reify GLFWCharCallbackI
(invoke [this _ codepoint]
(on-char window codepoint))))
(GLFW/glfwSetFramebufferSizeCallback
(reify GLFWFramebufferSizeCallbackI
(invoke [this _ width height]
(on-resize window width height))))))
(defn ->window []
(when-not (GLFW/glfwInit)
(throw (Exception. "Unable to initialize GLFW")))
(GLFW/glfwWindowHint GLFW/GLFW_VISIBLE GLFW/GLFW_FALSE)
(GLFW/glfwWindowHint GLFW/GLFW_RESIZABLE GLFW/GLFW_TRUE)
(GLFW/glfwWindowHint GLFW/GLFW_CONTEXT_VERSION_MAJOR 4)
(GLFW/glfwWindowHint GLFW/GLFW_CONTEXT_VERSION_MINOR 1)
(GLFW/glfwWindowHint GLFW/GLFW_OPENGL_FORWARD_COMPAT GL41/GL_TRUE)
(GLFW/glfwWindowHint GLFW/GLFW_OPENGL_PROFILE GLFW/GLFW_OPENGL_CORE_PROFILE)
(if-let [window (GLFW/glfwCreateWindow 1024 768 "Hello, world!" 0 0)]
(do
(GLFW/glfwMakeContextCurrent window)
(GLFW/glfwSwapInterval 1)
(GL/createCapabilities)
(->Window window))
(throw (Exception. "Failed to create window"))))
(defn start [game window]
(let [handle (:handle window)
game (assoc game :delta-time 0 :total-time 0)]
(GLFW/glfwShowWindow handle)
(listen-for-events window)
(c/init game)
; uncomment this to hear music when the game begins!
;(play-music!)
(loop [game game]
(when-not (GLFW/glfwWindowShouldClose handle)
(let [ts (GLFW/glfwGetTime)
game (assoc game
:delta-time (- ts (:total-time game))
:total-time ts)
game (on-tick window game)]
(GLFW/glfwSwapBuffers handle)
(GLFW/glfwPollEvents)
(recur game))))
(Callbacks/glfwFreeCallbacks handle)
(GLFW/glfwDestroyWindow handle)
(GLFW/glfwTerminate)))
(defn -main [& args]
(let [window (->window)]
(start (pc/->game (:handle window)) window)))
| null | https://raw.githubusercontent.com/oakes/Nightcode/2e112c59cddc5fdec96059a08912c73b880f9ae8/resources/leiningen/new/play_cljc/start.clj | clojure | uncomment this to hear music when the game begins!
(play-music!) | (ns {{name}}.start
(:require [{{name}}.{{core-name}} :as c]
[{{name}}.music :as m]
[play-cljc.gl.core :as pc])
(:import [org.lwjgl.glfw GLFW Callbacks
GLFWCursorPosCallbackI GLFWKeyCallbackI GLFWMouseButtonCallbackI
GLFWCharCallbackI GLFWFramebufferSizeCallbackI]
[org.lwjgl.opengl GL GL41]
[org.lwjgl.system MemoryUtil]
[javax.sound.sampled AudioSystem Clip])
(:gen-class))
(defn play-music! []
(doto (AudioSystem/getClip)
(.open (AudioSystem/getAudioInputStream (m/build-for-clj)))
(.loop Clip/LOOP_CONTINUOUSLY)
(.start)))
(defn mousecode->keyword [mousecode]
(condp = mousecode
GLFW/GLFW_MOUSE_BUTTON_LEFT :left
GLFW/GLFW_MOUSE_BUTTON_RIGHT :right
nil))
(defn on-mouse-move! [window xpos ypos]
(let [*fb-width (MemoryUtil/memAllocInt 1)
*fb-height (MemoryUtil/memAllocInt 1)
*window-width (MemoryUtil/memAllocInt 1)
*window-height (MemoryUtil/memAllocInt 1)
_ (GLFW/glfwGetFramebufferSize window *fb-width *fb-height)
_ (GLFW/glfwGetWindowSize window *window-width *window-height)
fb-width (.get *fb-width)
fb-height (.get *fb-height)
window-width (.get *window-width)
window-height (.get *window-height)
width-ratio (/ fb-width window-width)
height-ratio (/ fb-height window-height)
x (* xpos width-ratio)
y (* ypos height-ratio)]
(MemoryUtil/memFree *fb-width)
(MemoryUtil/memFree *fb-height)
(MemoryUtil/memFree *window-width)
(MemoryUtil/memFree *window-height)
(swap! c/*state assoc :mouse-x x :mouse-y y)))
(defn on-mouse-click! [window button action mods]
(swap! c/*state assoc :mouse-button (when (= action GLFW/GLFW_PRESS)
(mousecode->keyword button))))
(defn keycode->keyword [keycode]
(condp = keycode
GLFW/GLFW_KEY_LEFT :left
GLFW/GLFW_KEY_RIGHT :right
GLFW/GLFW_KEY_UP :up
GLFW/GLFW_KEY_DOWN :down
nil))
(defn on-key! [window keycode scancode action mods]
(when-let [k (keycode->keyword keycode)]
(condp = action
GLFW/GLFW_PRESS (swap! c/*state update :pressed-keys conj k)
GLFW/GLFW_RELEASE (swap! c/*state update :pressed-keys disj k)
nil)))
(defn on-char! [window codepoint])
(defn on-resize! [window width height])
(defprotocol Events
(on-mouse-move [this xpos ypos])
(on-mouse-click [this button action mods])
(on-key [this keycode scancode action mods])
(on-char [this codepoint])
(on-resize [this width height])
(on-tick [this game]))
(defrecord Window [handle])
(extend-type Window
Events
(on-mouse-move [{:keys [handle]} xpos ypos]
(on-mouse-move! handle xpos ypos))
(on-mouse-click [{:keys [handle]} button action mods]
(on-mouse-click! handle button action mods))
(on-key [{:keys [handle]} keycode scancode action mods]
(on-key! handle keycode scancode action mods))
(on-char [{:keys [handle]} codepoint]
(on-char! handle codepoint))
(on-resize [{:keys [handle]} width height]
(on-resize! handle width height))
(on-tick [this game]
(c/tick game)))
(defn listen-for-events [{:keys [handle] :as window}]
(doto handle
(GLFW/glfwSetCursorPosCallback
(reify GLFWCursorPosCallbackI
(invoke [this _ xpos ypos]
(on-mouse-move window xpos ypos))))
(GLFW/glfwSetMouseButtonCallback
(reify GLFWMouseButtonCallbackI
(invoke [this _ button action mods]
(on-mouse-click window button action mods))))
(GLFW/glfwSetKeyCallback
(reify GLFWKeyCallbackI
(invoke [this _ keycode scancode action mods]
(on-key window keycode scancode action mods))))
(GLFW/glfwSetCharCallback
(reify GLFWCharCallbackI
(invoke [this _ codepoint]
(on-char window codepoint))))
(GLFW/glfwSetFramebufferSizeCallback
(reify GLFWFramebufferSizeCallbackI
(invoke [this _ width height]
(on-resize window width height))))))
(defn ->window []
(when-not (GLFW/glfwInit)
(throw (Exception. "Unable to initialize GLFW")))
(GLFW/glfwWindowHint GLFW/GLFW_VISIBLE GLFW/GLFW_FALSE)
(GLFW/glfwWindowHint GLFW/GLFW_RESIZABLE GLFW/GLFW_TRUE)
(GLFW/glfwWindowHint GLFW/GLFW_CONTEXT_VERSION_MAJOR 4)
(GLFW/glfwWindowHint GLFW/GLFW_CONTEXT_VERSION_MINOR 1)
(GLFW/glfwWindowHint GLFW/GLFW_OPENGL_FORWARD_COMPAT GL41/GL_TRUE)
(GLFW/glfwWindowHint GLFW/GLFW_OPENGL_PROFILE GLFW/GLFW_OPENGL_CORE_PROFILE)
(if-let [window (GLFW/glfwCreateWindow 1024 768 "Hello, world!" 0 0)]
(do
(GLFW/glfwMakeContextCurrent window)
(GLFW/glfwSwapInterval 1)
(GL/createCapabilities)
(->Window window))
(throw (Exception. "Failed to create window"))))
(defn start [game window]
(let [handle (:handle window)
game (assoc game :delta-time 0 :total-time 0)]
(GLFW/glfwShowWindow handle)
(listen-for-events window)
(c/init game)
(loop [game game]
(when-not (GLFW/glfwWindowShouldClose handle)
(let [ts (GLFW/glfwGetTime)
game (assoc game
:delta-time (- ts (:total-time game))
:total-time ts)
game (on-tick window game)]
(GLFW/glfwSwapBuffers handle)
(GLFW/glfwPollEvents)
(recur game))))
(Callbacks/glfwFreeCallbacks handle)
(GLFW/glfwDestroyWindow handle)
(GLFW/glfwTerminate)))
(defn -main [& args]
(let [window (->window)]
(start (pc/->game (:handle window)) window)))
|
70b786985dcdf5283eb5fd549ebc3065bac30645d982870c712c3b6f55d6daba | input-output-hk/goblins | Core.hs | {-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | The core typeclasses and associated methods of goblins.
module Test.Goblin.Core
( module Test.Goblin.Core
, (<$$>)
, (<**>)
) where
import Control.Monad (replicateM)
import Control.Monad.Trans.State.Strict (State)
import Data.Typeable (Typeable)
import Data.TypeRepMap (TypeRepMap)
import qualified Data.TypeRepMap as TM
import Hedgehog (Gen)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Lens.Micro.Mtl ((%=), (.=), use)
import Lens.Micro.TH (makeLenses)
import Moo.GeneticAlgorithm.Types (Genome, Population)
import Test.Goblin.Util
-- | The state we carry as we perform goblins actions.
data GoblinData g = GoblinData
{ -- | Remaining genes, controlling how a goblin operates.
_genes :: !(Genome g)
-- | A goblin's bag of tricks contains items of many differnt types. When
-- tinkering, a goblin (depending on its genome) might look in its bag of
-- tricks to see whether it has anything of the appropriate type to replace
-- what it's currently tinkering with (or, depending on the type, do
-- something different - for example, utilise a monoid instance to add
-- things together).
, _bagOfTricks :: !(TypeRepMap [])
}
makeLenses 'GoblinData
| Tinker monad .
type TinkerM g = State (GoblinData g)
| The interface to goblins . This class defines two actions
-- - `tinker`ing with an existing value
-- - `conjure`ing a new value
class (GeneOps g, Typeable a) => Goblin g a where
-- | Tinker with an item of type 'a'.
tinker :: Gen a -> TinkerM g (Gen a)
-- | As well as tinkering, goblins can conjure fresh items into existence.
conjure :: TinkerM g a
-- | Helper function to save a value in the bagOfTricks, and return it.
saveInBagOfTricks :: forall g a. Typeable a => a -> TinkerM g a
saveInBagOfTricks x = do
bagOfTricks %= consOrInsert
pure x
where
consOrInsert :: TypeRepMap [] -> TypeRepMap []
consOrInsert trm = if TM.member @a trm
then TM.adjust (x:) trm
else TM.insert [x] trm
-- | Construct a tinker function given a set of possible things to do.
--
Each ' toy ' is a function taking the original value and one grabbed from the
-- bag of tricks or conjured.
tinkerWithToys
:: (AddShrinks a, Goblin g a)
=> [Gen a -> Gen a -> Gen a]
-> (Gen a -> TinkerM g (Gen a))
tinkerWithToys toys a =
let
defaultToys = [const, flip const]
allToys = defaultToys ++ toys
in tinkerRummagedOrConjureOrSave $ do
toy <- (allToys !!) <$> geneListIndex allToys
toy a <$> tinkerRummagedOrConjure
-- | Either tinker with a rummaged value, conjure a new value, or save the
-- argument in the bagOfTricks and return it.
tinkerRummagedOrConjureOrSave :: (Goblin g a, AddShrinks a)
=> TinkerM g (Gen a) -> TinkerM g (Gen a)
tinkerRummagedOrConjureOrSave m =
onGene tinkerRummagedOrConjure (saveInBagOfTricks =<< m)
--------------------------------------------------------------------------------
-- Gene operations
--------------------------------------------------------------------------------
-- | Read (and consume) a gene from the genome.
transcribeGene :: TinkerM g g
transcribeGene = do
g <- use genes
case g of
[] -> error "Genome has run out! Try increasing the size of the genome."
(x : xs) -> do
genes .= xs
return x
-- | A typeclass for actions over genomes.
class GeneOps g where
| Choose between two actions based on the value of a gene .
onGene
:: TinkerM g a
-- ^ When gene is on.
-> TinkerM g a
-- ^ When gene is off.
-> TinkerM g a
-- | Transcribe sufficient genes to get an integer in the range [0..n].
transcribeGenesAsInt
:: Int
-> TinkerM g Int
--------------------------------------------------------------------------------
-- Bag of tricks
--------------------------------------------------------------------------------
-- | Fetch something from the bag of tricks if there's something there.
rummage :: forall a g . (GeneOps g, Typeable a) => TinkerM g (Maybe a)
rummage = do
bag <- use bagOfTricks
case TM.lookup bag of
Nothing -> pure Nothing
@mhueschen : \/ will not shrink , I believe
Just xs ->
(xs !!) <$> geneListIndex xs
-- | Fetch everything from the bag of tricks.
rummageAll :: forall a g . Typeable a => TinkerM g [a]
rummageAll = do
bag <- use bagOfTricks
case TM.lookup bag of
Nothing -> pure []
@mhueschen : \/ will not shrink , I believe
Just xs -> pure xs
-- | Fetch something from the bag of tricks, or else conjure it up.
rummageOrConjure :: forall a g . Goblin g a => TinkerM g a
rummageOrConjure = maybe conjure pure =<< rummage
-- | Attempt to rummage. If a value is available, either tinker with it or
-- leave it intact. If no value is available, conjure a fresh one and add
-- shrinks to it.
tinkerRummagedOrConjure :: forall a g . (Goblin g a, AddShrinks a)
=> TinkerM g (Gen a)
tinkerRummagedOrConjure = do
mR <- rummage
case mR of
Nothing -> addShrinks <$> conjure
Just v -> onGene (tinker v) (pure v)
--------------------------------------------------------------------------------
-- AddShrinks class
--------------------------------------------------------------------------------
| Whereas ` pure ` creates a Hedgehog tree with no shrinks , ` `
-- creates a tree with shrinks.
class AddShrinks a where
addShrinks :: a -> Gen a
default addShrinks
:: Enum a
=> a
-> Gen a
addShrinks = Gen.shrink shrinkEnum . pure
| Use an instance to create a shrink tree which shrinks towards
-- `toEnum 0`.
shrinkEnum :: Enum a => a -> [a]
shrinkEnum x = toEnum <$>
if e == 0
then []
else tail (enumFromThenTo e e1 0)
where
absDecr v = signum v * (abs v - 1)
e = fromEnum x
e1 = absDecr e
--------------------------------------------------------------------------------
SeedGoblin class
--------------------------------------------------------------------------------
-- | Recur down a datatype, adding the sub-datatypes to the `TinkerM` `TypeRepMap`
class SeedGoblin a where
-- | Recur down a type, adding elements to the TypeRepMap
seeder :: a -> TinkerM g ()
default seeder
:: Typeable a
=> a
-> TinkerM g ()
seeder x = () <$ saveInBagOfTricks x
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
-- | Spawn a goblin from a given genome and a bag of tricks.
mkGoblin :: Genome g -> TypeRepMap [] -> GoblinData g
mkGoblin = GoblinData
-- | Spawn a goblin from a genome, with an empty TypeRepMap.
mkEmptyGoblin :: Genome g -> GoblinData g
mkEmptyGoblin genome = GoblinData genome TM.empty
-- | Use the genome to generate an index within the bounds
-- of the provided list.
geneListIndex :: GeneOps g => [a] -> TinkerM g Int
geneListIndex xs = transcribeGenesAsInt (length xs - 1)
-- | Convenience Hedgehog generator.
genPopulation :: Gen (Population Bool)
genPopulation = do
genomeSize <- Gen.int (Range.linear 0 1000)
Gen.list (Range.linear 0 300) $ do
genome <- replicateM genomeSize Gen.bool
(,) <$> pure genome <*> Gen.double (Range.constant 0 (10.0^^(3::Int)))
| null | https://raw.githubusercontent.com/input-output-hk/goblins/cde90a2b27f79187ca8310b6549331e59595e7ba/src/Test/Goblin/Core.hs | haskell | # LANGUAGE DefaultSignatures #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
# LANGUAGE ScopedTypeVariables #
| The core typeclasses and associated methods of goblins.
| The state we carry as we perform goblins actions.
| Remaining genes, controlling how a goblin operates.
| A goblin's bag of tricks contains items of many differnt types. When
tinkering, a goblin (depending on its genome) might look in its bag of
tricks to see whether it has anything of the appropriate type to replace
what it's currently tinkering with (or, depending on the type, do
something different - for example, utilise a monoid instance to add
things together).
- `tinker`ing with an existing value
- `conjure`ing a new value
| Tinker with an item of type 'a'.
| As well as tinkering, goblins can conjure fresh items into existence.
| Helper function to save a value in the bagOfTricks, and return it.
| Construct a tinker function given a set of possible things to do.
bag of tricks or conjured.
| Either tinker with a rummaged value, conjure a new value, or save the
argument in the bagOfTricks and return it.
------------------------------------------------------------------------------
Gene operations
------------------------------------------------------------------------------
| Read (and consume) a gene from the genome.
| A typeclass for actions over genomes.
^ When gene is on.
^ When gene is off.
| Transcribe sufficient genes to get an integer in the range [0..n].
------------------------------------------------------------------------------
Bag of tricks
------------------------------------------------------------------------------
| Fetch something from the bag of tricks if there's something there.
| Fetch everything from the bag of tricks.
| Fetch something from the bag of tricks, or else conjure it up.
| Attempt to rummage. If a value is available, either tinker with it or
leave it intact. If no value is available, conjure a fresh one and add
shrinks to it.
------------------------------------------------------------------------------
AddShrinks class
------------------------------------------------------------------------------
creates a tree with shrinks.
`toEnum 0`.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Recur down a datatype, adding the sub-datatypes to the `TinkerM` `TypeRepMap`
| Recur down a type, adding elements to the TypeRepMap
------------------------------------------------------------------------------
Helpers
------------------------------------------------------------------------------
| Spawn a goblin from a given genome and a bag of tricks.
| Spawn a goblin from a genome, with an empty TypeRepMap.
| Use the genome to generate an index within the bounds
of the provided list.
| Convenience Hedgehog generator. | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Test.Goblin.Core
( module Test.Goblin.Core
, (<$$>)
, (<**>)
) where
import Control.Monad (replicateM)
import Control.Monad.Trans.State.Strict (State)
import Data.Typeable (Typeable)
import Data.TypeRepMap (TypeRepMap)
import qualified Data.TypeRepMap as TM
import Hedgehog (Gen)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Lens.Micro.Mtl ((%=), (.=), use)
import Lens.Micro.TH (makeLenses)
import Moo.GeneticAlgorithm.Types (Genome, Population)
import Test.Goblin.Util
data GoblinData g = GoblinData
_genes :: !(Genome g)
, _bagOfTricks :: !(TypeRepMap [])
}
makeLenses 'GoblinData
| Tinker monad .
type TinkerM g = State (GoblinData g)
| The interface to goblins . This class defines two actions
class (GeneOps g, Typeable a) => Goblin g a where
tinker :: Gen a -> TinkerM g (Gen a)
conjure :: TinkerM g a
saveInBagOfTricks :: forall g a. Typeable a => a -> TinkerM g a
saveInBagOfTricks x = do
bagOfTricks %= consOrInsert
pure x
where
consOrInsert :: TypeRepMap [] -> TypeRepMap []
consOrInsert trm = if TM.member @a trm
then TM.adjust (x:) trm
else TM.insert [x] trm
Each ' toy ' is a function taking the original value and one grabbed from the
tinkerWithToys
:: (AddShrinks a, Goblin g a)
=> [Gen a -> Gen a -> Gen a]
-> (Gen a -> TinkerM g (Gen a))
tinkerWithToys toys a =
let
defaultToys = [const, flip const]
allToys = defaultToys ++ toys
in tinkerRummagedOrConjureOrSave $ do
toy <- (allToys !!) <$> geneListIndex allToys
toy a <$> tinkerRummagedOrConjure
tinkerRummagedOrConjureOrSave :: (Goblin g a, AddShrinks a)
=> TinkerM g (Gen a) -> TinkerM g (Gen a)
tinkerRummagedOrConjureOrSave m =
onGene tinkerRummagedOrConjure (saveInBagOfTricks =<< m)
transcribeGene :: TinkerM g g
transcribeGene = do
g <- use genes
case g of
[] -> error "Genome has run out! Try increasing the size of the genome."
(x : xs) -> do
genes .= xs
return x
class GeneOps g where
| Choose between two actions based on the value of a gene .
onGene
:: TinkerM g a
-> TinkerM g a
-> TinkerM g a
transcribeGenesAsInt
:: Int
-> TinkerM g Int
rummage :: forall a g . (GeneOps g, Typeable a) => TinkerM g (Maybe a)
rummage = do
bag <- use bagOfTricks
case TM.lookup bag of
Nothing -> pure Nothing
@mhueschen : \/ will not shrink , I believe
Just xs ->
(xs !!) <$> geneListIndex xs
rummageAll :: forall a g . Typeable a => TinkerM g [a]
rummageAll = do
bag <- use bagOfTricks
case TM.lookup bag of
Nothing -> pure []
@mhueschen : \/ will not shrink , I believe
Just xs -> pure xs
rummageOrConjure :: forall a g . Goblin g a => TinkerM g a
rummageOrConjure = maybe conjure pure =<< rummage
tinkerRummagedOrConjure :: forall a g . (Goblin g a, AddShrinks a)
=> TinkerM g (Gen a)
tinkerRummagedOrConjure = do
mR <- rummage
case mR of
Nothing -> addShrinks <$> conjure
Just v -> onGene (tinker v) (pure v)
| Whereas ` pure ` creates a Hedgehog tree with no shrinks , ` `
class AddShrinks a where
addShrinks :: a -> Gen a
default addShrinks
:: Enum a
=> a
-> Gen a
addShrinks = Gen.shrink shrinkEnum . pure
| Use an instance to create a shrink tree which shrinks towards
shrinkEnum :: Enum a => a -> [a]
shrinkEnum x = toEnum <$>
if e == 0
then []
else tail (enumFromThenTo e e1 0)
where
absDecr v = signum v * (abs v - 1)
e = fromEnum x
e1 = absDecr e
SeedGoblin class
class SeedGoblin a where
seeder :: a -> TinkerM g ()
default seeder
:: Typeable a
=> a
-> TinkerM g ()
seeder x = () <$ saveInBagOfTricks x
mkGoblin :: Genome g -> TypeRepMap [] -> GoblinData g
mkGoblin = GoblinData
mkEmptyGoblin :: Genome g -> GoblinData g
mkEmptyGoblin genome = GoblinData genome TM.empty
geneListIndex :: GeneOps g => [a] -> TinkerM g Int
geneListIndex xs = transcribeGenesAsInt (length xs - 1)
genPopulation :: Gen (Population Bool)
genPopulation = do
genomeSize <- Gen.int (Range.linear 0 1000)
Gen.list (Range.linear 0 300) $ do
genome <- replicateM genomeSize Gen.bool
(,) <$> pure genome <*> Gen.double (Range.constant 0 (10.0^^(3::Int)))
|
35f5d6981119da0b1739a93528b64661090f5f66ef34403e206f3dddb851d64c | thephoeron/baphomet | generic-interface.lisp | Copyright ( c ) 2022 , " the Phoeron " < >
Released under the MIT License . See baphomet / LICENSE for more information .
(in-package :common-lisp/generic-interface)
(defgeneric instancep (instance)
(:documentation ""))
(defgeneric new (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric redefine (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric copy (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric initialize (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric collapse (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric invoke (instance &rest args &key &allow-other-keys)
(:documentation ""))
| null | https://raw.githubusercontent.com/thephoeron/baphomet/5ac1e33b5e8bac07be1ac6f9028e21b05f1205e0/type-packages/generic-interface.lisp | lisp | Copyright ( c ) 2022 , " the Phoeron " < >
Released under the MIT License . See baphomet / LICENSE for more information .
(in-package :common-lisp/generic-interface)
(defgeneric instancep (instance)
(:documentation ""))
(defgeneric new (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric redefine (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric copy (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric initialize (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric collapse (instance &rest args &key &allow-other-keys)
(:documentation ""))
(defgeneric invoke (instance &rest args &key &allow-other-keys)
(:documentation ""))
| |
b0b52c8afa5e68f467d051498bab61673b61e6f355902a5ca816dcf898cb84ad | typelead/eta | T4310.hs | # LANGUAGE TypeFamilies , RankNTypes , ScopedTypeVariables , KindSignatures #
module T4310 where
import GHC.ST
type family Mutable a :: * -> * -> *
data New v a = New (forall s. ST s (Mutable v s a))
create :: (forall s. ST s (Mutable v s a)) -> New v a
create = New
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/T4310.hs | haskell | # LANGUAGE TypeFamilies , RankNTypes , ScopedTypeVariables , KindSignatures #
module T4310 where
import GHC.ST
type family Mutable a :: * -> * -> *
data New v a = New (forall s. ST s (Mutable v s a))
create :: (forall s. ST s (Mutable v s a)) -> New v a
create = New
| |
a1408d450caf3569195062c9b7cc277ca702363fd64683646fa059de8319557b | faylang/fay | HidePreludeImport_Import.hs | module HidePreludeImport_Import where
last :: Double
last = 1
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/HidePreludeImport_Import.hs | haskell | module HidePreludeImport_Import where
last :: Double
last = 1
| |
b63be5e3fdac043378b39083fc7f48a0744a252632f7bb6cedc21558ef465cc5 | mirage/ocaml-cohttp | lwt_unix_server_new.ml | open Lwt.Syntax
module Context = Cohttp_server_lwt_unix.Context
module Body = Cohttp_server_lwt_unix.Body
let text = String.make 2053 'a'
let server_callback ctx =
Lwt.join
[
Context.discard_body ctx;
Context.respond ctx (Http.Response.make ()) (Body.string text);
]
let main () =
let* _server =
let listen_address = Unix.(ADDR_INET (inet_addr_loopback, 8080)) in
let server =
Cohttp_server_lwt_unix.create
~on_exn:(fun exn ->
Format.eprintf "unexpected:@.%s@." (Printexc.to_string exn))
server_callback
in
Lwt_io.establish_server_with_client_address ~backlog:10_000 listen_address
(fun _addr ch -> Cohttp_server_lwt_unix.handle_connection server ch)
in
let forever, _ = Lwt.wait () in
forever
let () =
Printexc.record_backtrace true;
ignore (Lwt_main.run (main ()))
| null | https://raw.githubusercontent.com/mirage/ocaml-cohttp/c4e7da95a44e072f1e43e6b3605f599c29002ed5/cohttp-bench/lwt_unix_server_new.ml | ocaml | open Lwt.Syntax
module Context = Cohttp_server_lwt_unix.Context
module Body = Cohttp_server_lwt_unix.Body
let text = String.make 2053 'a'
let server_callback ctx =
Lwt.join
[
Context.discard_body ctx;
Context.respond ctx (Http.Response.make ()) (Body.string text);
]
let main () =
let* _server =
let listen_address = Unix.(ADDR_INET (inet_addr_loopback, 8080)) in
let server =
Cohttp_server_lwt_unix.create
~on_exn:(fun exn ->
Format.eprintf "unexpected:@.%s@." (Printexc.to_string exn))
server_callback
in
Lwt_io.establish_server_with_client_address ~backlog:10_000 listen_address
(fun _addr ch -> Cohttp_server_lwt_unix.handle_connection server ch)
in
let forever, _ = Lwt.wait () in
forever
let () =
Printexc.record_backtrace true;
ignore (Lwt_main.run (main ()))
| |
e2cf470f8ec6ac9f93711c656f1b6b89c3406502aefd1fb4c387b7715b4bb181 | mstksg/inCode | todo-cmd.hs | -- | -a-todo-gui-application-with-auto-on
--
-- You probably will also need the actual application logic, at
-- -samples/auto/Todo.hs
--
-- Recommended to run with cabal sandboxes:
--
-- $ cabal sandbox init
-- $ cabal install auto
$ cabal exec
--
module Main (main) where
import Control.Auto
import Control.Auto.Interval
import Control.Monad
import Data.IntMap (IntMap)
import Data.Maybe
import Prelude hiding ((.), id)
import Text.Read
import Todo
import qualified Data.IntMap as IM
-- | Parse a string input.
parseInp :: String -> Maybe TodoInp
parseInp = p . words
where
p ("A":xs) = Just (IAdd (unwords xs))
p ("D":n:_) = onId n CDelete
p ("C":n:_) = onId n (CComplete True)
p ("U":n:_) = onId n (CComplete False)
p ("P":n:_) = onId n CPrune
p ("M":n:xs) = onId n (CModify (unwords xs))
p _ = Nothing
onId :: String -> TaskCmd -> Maybe TodoInp
onId "*" te = Just (IAll te)
onId n te = (`ITask` te) <$> readMaybe n
| Just for command line testing use , turning the IntMap into a String .
formatTodo :: IntMap Task -> String
formatTodo = unlines . map format . IM.toList
where
format (n, Task desc compl) = concat [ show n
, ". ["
, if compl then "X" else " "
, "] "
, desc
]
main :: IO ()
main = do
putStrLn "Enter command! 'A descr' or '[D/C/U/P/M] [id/*]'"
interactAuto takes an Interval ; ` toOn ` gives
-- one that runs forever
toOn
-- default output value on bad command
. fromBlips "Bad command!"
-- run `formatTodo <$> todoApp` on emitted commands
. perBlip (formatTodo <$> todoApp)
emit when input is
. emitJusts parseInp
| null | https://raw.githubusercontent.com/mstksg/inCode/e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a/code-samples/auto/todo-cmd.hs | haskell | | -a-todo-gui-application-with-auto-on
You probably will also need the actual application logic, at
-samples/auto/Todo.hs
Recommended to run with cabal sandboxes:
$ cabal sandbox init
$ cabal install auto
| Parse a string input.
one that runs forever
default output value on bad command
run `formatTodo <$> todoApp` on emitted commands | $ cabal exec
module Main (main) where
import Control.Auto
import Control.Auto.Interval
import Control.Monad
import Data.IntMap (IntMap)
import Data.Maybe
import Prelude hiding ((.), id)
import Text.Read
import Todo
import qualified Data.IntMap as IM
parseInp :: String -> Maybe TodoInp
parseInp = p . words
where
p ("A":xs) = Just (IAdd (unwords xs))
p ("D":n:_) = onId n CDelete
p ("C":n:_) = onId n (CComplete True)
p ("U":n:_) = onId n (CComplete False)
p ("P":n:_) = onId n CPrune
p ("M":n:xs) = onId n (CModify (unwords xs))
p _ = Nothing
onId :: String -> TaskCmd -> Maybe TodoInp
onId "*" te = Just (IAll te)
onId n te = (`ITask` te) <$> readMaybe n
| Just for command line testing use , turning the IntMap into a String .
formatTodo :: IntMap Task -> String
formatTodo = unlines . map format . IM.toList
where
format (n, Task desc compl) = concat [ show n
, ". ["
, if compl then "X" else " "
, "] "
, desc
]
main :: IO ()
main = do
putStrLn "Enter command! 'A descr' or '[D/C/U/P/M] [id/*]'"
interactAuto takes an Interval ; ` toOn ` gives
toOn
. fromBlips "Bad command!"
. perBlip (formatTodo <$> todoApp)
emit when input is
. emitJusts parseInp
|
fd2d4da9ac6ab75f341a51dd2acc2d8e11675fbc3e588b546fa5c4cd14ed0278 | uwplse/oddity | routes.clj | (ns oddity.routes
(:require [compojure.core :refer [GET routes]]
[compojure.route :refer [not-found resources]]
[hiccup.page :refer [include-js include-css html5]]
[config.core :refer [env]]
[oddity.config :refer [client-config]]))
(def mount-target
[:div#app
[:h3 "Loading..."]])
(defn head []
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css (if (env :dev) "/css/site.css" "/css/site.min.css"))
(include-css "/css/fontawesome-all.min.css")
(include-css "")])
(defn loading-page [config]
(html5
(head)
[:body {:class "body-container"}
[:div#config {:data-config (pr-str (client-config config))}]
mount-target
(include-js "/js/app.js")]))
(defn app-routes [config]
(fn [endpoint]
(routes
(GET "/" [] (loading-page config))
(GET "/about" [] (loading-page config))
(resources "/")
(not-found "Not Found"))))
| null | https://raw.githubusercontent.com/uwplse/oddity/81c1a6af203a0d8e71138a27655e3c4003357127/oddity/src/clj/oddity/routes.clj | clojure | (ns oddity.routes
(:require [compojure.core :refer [GET routes]]
[compojure.route :refer [not-found resources]]
[hiccup.page :refer [include-js include-css html5]]
[config.core :refer [env]]
[oddity.config :refer [client-config]]))
(def mount-target
[:div#app
[:h3 "Loading..."]])
(defn head []
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css (if (env :dev) "/css/site.css" "/css/site.min.css"))
(include-css "/css/fontawesome-all.min.css")
(include-css "")])
(defn loading-page [config]
(html5
(head)
[:body {:class "body-container"}
[:div#config {:data-config (pr-str (client-config config))}]
mount-target
(include-js "/js/app.js")]))
(defn app-routes [config]
(fn [endpoint]
(routes
(GET "/" [] (loading-page config))
(GET "/about" [] (loading-page config))
(resources "/")
(not-found "Not Found"))))
| |
776b444feaae4539f3e5c5d5bbc363454e6bf4d88ff9662ac249dd9714dfac37 | daveyarwood/music-theory | chord.cljc | (ns music-theory.chord
(:require [clojure.string :as str]
[music-theory.note :refer (->note interval+ interval-)]
[music-theory.util :refer (error parse-int)]))
(def ^:private chord-intervals
{"" [:M3 :m3] ; major
"M" [:M3 :m3]
"maj" [:M3 :m3]
"m" [:m3 :M3] ; minor
"min" [:m3 :M3]
"dim" [:m3 :m3] ; diminished
"°" [:m3 :m3]
"aug" [:M3 :M3] ; augmented
"+" [:M3 :M3]
"+5" [:M3 :M3]
fifth
major sixth
"M6" [:M3 :m3 :M2]
"maj6" [:M3 :m3 :M2]
minor sixth
"min6" [:m3 :M3 :M2]
major seventh
"maj7" [:M3 :m3 :M3]
dominant seventh
"dom7" [:M3 :m3 :m3]
minor seventh
"min7" [:m3 :M3 :m3]
half diminished seventh
"ø7" [:m3 :m3 :M3]
"m7b5" [:m3 :m3 :M3]
fully diminished seventh
"dim7" [:m3 :m3 :m3]
minor - major seventh
"min+7" [:m3 :M3 :M3]
augmented - minor seventh
"+7" [:M3 :M3 :d3]
"7+5" [:M3 :M3 :d3]
"7#5" [:M3 :M3 :d3]
major - minor w/ lowered fifth
major ninth
"maj9" [:M3 :m3 :M3 :m3]
dominant ninth
"dom9" [:M3 :m3 :m3 :M3]
minor - major ninth
"minmaj9" [:m3 :M3 :M3 :m3]
minor ninth
"min9" [:m3 :M3 :m3 :M3]
augmented major ninth
"augmaj9" [:M3 :M3 :m3 :m3]
augmented dominant ninth
"aug9" [:M3 :M3 :d3 :M3]
"9#5" [:M3 :M3 :d3 :M3]
half diminished ninth
half diminished minor ninth
diminished ninth
"dim9" [:m3 :m3 :m3 :A3]
diminished minor ninth
"dimb9" [:m3 :m3 :m3 :M3]
"dimmin9" [:m3 :m3 :m3 :M3]
major eleventh
"maj11" [:M3 :m3 :M3 :m3 :m3]
dominant eleventh
"dom11" [:M3 :m3 :m3 :M3 :m3]
minor - major eleventh
"minmaj11" [:m3 :M3 :M3 :m3 :m3]
minor eleventh
"min11" [:m3 :M3 :m3 :M3 :m3]
augmented major eleventh
"augmaj11" [:M3 :M3 :m3 :m3 :m3]
augmented dominant eleventh
"aug11" [:M3 :M3 :d3 :M3 :m3]
"11#5" [:M3 :M3 :d3 :M3 :m3]
half diminished eleventh
diminished eleventh
"dim11" [:m3 :m3 :m3 :M3 :m3]
major thirteenth
"maj13" [:M3 :m3 :M3 :m3 :m3 :M3]
dominant thirteenth
"dom13" [:M3 :m3 :m3 :M3 :m3 :M3]
minor - major thirteenth
"minmaj13" [:m3 :M3 :M3 :m3 :m3 :M3]
minor thirteenth
"min13" [:m3 :M3 :m3 :M3 :m3 :M3]
augmented major thirteenth
"augmaj13" [:M3 :M3 :m3 :m3 :m3 :M3]
augmented dominant thirteenth
"aug13" [:M3 :M3 :d3 :M3 :m3 :M3]
"13#5" [:M3 :M3 :d3 :M3 :m3 :M3]
half diminished thirteenth
diminished thirteenth
"dim13" [:m3 :m3 :m3 :M3 :m3 :M3]
})
(defn- find-inversion
"Given a bass (lowest) note and a chord (as a sequence of notes), returns
either the number of the inversion that would put that note in the bass,
or nil if that note isn't in the chord.
e.g.
= > 1
(find-inversion \"F#\" [:C4 :E4 :G4]) ;=> nil"
[bass chord]
(first (keep-indexed (fn [i note]
(when (str/starts-with? (name note) bass) i))
chord)))
(defn octave-span
"Returns the number of octaves spanned by a chord. The chord must be provided
as a sequence of notes.
e.g.
= > 1
= > 1
= > 2
= > 2
= > 3 "
[chord]
(let [[min max] ((juxt #(apply min %) #(apply max %))
(map #(:number (->note %)) chord))
span (- max min)]
(inc (quot span 12))))
(defn- invert-chord
[root-chord inversion]
(concat (drop inversion root-chord)
(map #(apply interval+ % (repeat (octave-span root-chord) :P8))
(take inversion root-chord))))
(defn build-chord
"Given a base (lowest) note and either:
- a sequence of intervals like :m3, :P5, etc.
- the name of a chord, like :Cmaj7
Returns a list of the notes in the chord, in order from lowest to highest."
[base-note x]
(if (coll? x)
(reductions interval+ base-note x)
(if-let [[_ root chord] (re-matches #"([A-G][#b]*)(.*)" (name x))]
(if-let [intervals (chord-intervals chord)]
(let [[_ bass octave] (re-matches #"([A-G][#b]*)(\d+)" (name base-note))]
(if (= root bass)
(build-chord base-note intervals)
(let [root-chord (build-chord (keyword (str root octave)) x)]
(if-let [inversion (find-inversion bass root-chord)]
(let [inverted-chord (invert-chord root-chord inversion)
octave (parse-int octave)
octave' (->> inverted-chord
first
name
(re-matches #"[A-G][#b]*(\d+)")
second
parse-int)]
(cond
(= octave octave')
inverted-chord
(= octave (inc octave'))
(map #(interval+ % :P8) inverted-chord)
(= octave (dec octave'))
(map #(interval- % :P8) inverted-chord)))
(error (str "There is no " bass " in a " (name x)))))))
(error (str "Unrecognized chord type: " chord)))
(error (str "Unrecognized chord symbol: " (name x))))))
| null | https://raw.githubusercontent.com/daveyarwood/music-theory/c58beb9fa6d290900afeff78ee4f86c875e393d7/src/music_theory/chord.cljc | clojure | major
minor
diminished
augmented
=> nil" | (ns music-theory.chord
(:require [clojure.string :as str]
[music-theory.note :refer (->note interval+ interval-)]
[music-theory.util :refer (error parse-int)]))
(def ^:private chord-intervals
"M" [:M3 :m3]
"maj" [:M3 :m3]
"min" [:m3 :M3]
"°" [:m3 :m3]
"+" [:M3 :M3]
"+5" [:M3 :M3]
fifth
major sixth
"M6" [:M3 :m3 :M2]
"maj6" [:M3 :m3 :M2]
minor sixth
"min6" [:m3 :M3 :M2]
major seventh
"maj7" [:M3 :m3 :M3]
dominant seventh
"dom7" [:M3 :m3 :m3]
minor seventh
"min7" [:m3 :M3 :m3]
half diminished seventh
"ø7" [:m3 :m3 :M3]
"m7b5" [:m3 :m3 :M3]
fully diminished seventh
"dim7" [:m3 :m3 :m3]
minor - major seventh
"min+7" [:m3 :M3 :M3]
augmented - minor seventh
"+7" [:M3 :M3 :d3]
"7+5" [:M3 :M3 :d3]
"7#5" [:M3 :M3 :d3]
major - minor w/ lowered fifth
major ninth
"maj9" [:M3 :m3 :M3 :m3]
dominant ninth
"dom9" [:M3 :m3 :m3 :M3]
minor - major ninth
"minmaj9" [:m3 :M3 :M3 :m3]
minor ninth
"min9" [:m3 :M3 :m3 :M3]
augmented major ninth
"augmaj9" [:M3 :M3 :m3 :m3]
augmented dominant ninth
"aug9" [:M3 :M3 :d3 :M3]
"9#5" [:M3 :M3 :d3 :M3]
half diminished ninth
half diminished minor ninth
diminished ninth
"dim9" [:m3 :m3 :m3 :A3]
diminished minor ninth
"dimb9" [:m3 :m3 :m3 :M3]
"dimmin9" [:m3 :m3 :m3 :M3]
major eleventh
"maj11" [:M3 :m3 :M3 :m3 :m3]
dominant eleventh
"dom11" [:M3 :m3 :m3 :M3 :m3]
minor - major eleventh
"minmaj11" [:m3 :M3 :M3 :m3 :m3]
minor eleventh
"min11" [:m3 :M3 :m3 :M3 :m3]
augmented major eleventh
"augmaj11" [:M3 :M3 :m3 :m3 :m3]
augmented dominant eleventh
"aug11" [:M3 :M3 :d3 :M3 :m3]
"11#5" [:M3 :M3 :d3 :M3 :m3]
half diminished eleventh
diminished eleventh
"dim11" [:m3 :m3 :m3 :M3 :m3]
major thirteenth
"maj13" [:M3 :m3 :M3 :m3 :m3 :M3]
dominant thirteenth
"dom13" [:M3 :m3 :m3 :M3 :m3 :M3]
minor - major thirteenth
"minmaj13" [:m3 :M3 :M3 :m3 :m3 :M3]
minor thirteenth
"min13" [:m3 :M3 :m3 :M3 :m3 :M3]
augmented major thirteenth
"augmaj13" [:M3 :M3 :m3 :m3 :m3 :M3]
augmented dominant thirteenth
"aug13" [:M3 :M3 :d3 :M3 :m3 :M3]
"13#5" [:M3 :M3 :d3 :M3 :m3 :M3]
half diminished thirteenth
diminished thirteenth
"dim13" [:m3 :m3 :m3 :M3 :m3 :M3]
})
(defn- find-inversion
"Given a bass (lowest) note and a chord (as a sequence of notes), returns
either the number of the inversion that would put that note in the bass,
or nil if that note isn't in the chord.
e.g.
= > 1
[bass chord]
(first (keep-indexed (fn [i note]
(when (str/starts-with? (name note) bass) i))
chord)))
(defn octave-span
"Returns the number of octaves spanned by a chord. The chord must be provided
as a sequence of notes.
e.g.
= > 1
= > 1
= > 2
= > 2
= > 3 "
[chord]
(let [[min max] ((juxt #(apply min %) #(apply max %))
(map #(:number (->note %)) chord))
span (- max min)]
(inc (quot span 12))))
(defn- invert-chord
[root-chord inversion]
(concat (drop inversion root-chord)
(map #(apply interval+ % (repeat (octave-span root-chord) :P8))
(take inversion root-chord))))
(defn build-chord
"Given a base (lowest) note and either:
- a sequence of intervals like :m3, :P5, etc.
- the name of a chord, like :Cmaj7
Returns a list of the notes in the chord, in order from lowest to highest."
[base-note x]
(if (coll? x)
(reductions interval+ base-note x)
(if-let [[_ root chord] (re-matches #"([A-G][#b]*)(.*)" (name x))]
(if-let [intervals (chord-intervals chord)]
(let [[_ bass octave] (re-matches #"([A-G][#b]*)(\d+)" (name base-note))]
(if (= root bass)
(build-chord base-note intervals)
(let [root-chord (build-chord (keyword (str root octave)) x)]
(if-let [inversion (find-inversion bass root-chord)]
(let [inverted-chord (invert-chord root-chord inversion)
octave (parse-int octave)
octave' (->> inverted-chord
first
name
(re-matches #"[A-G][#b]*(\d+)")
second
parse-int)]
(cond
(= octave octave')
inverted-chord
(= octave (inc octave'))
(map #(interval+ % :P8) inverted-chord)
(= octave (dec octave'))
(map #(interval- % :P8) inverted-chord)))
(error (str "There is no " bass " in a " (name x)))))))
(error (str "Unrecognized chord type: " chord)))
(error (str "Unrecognized chord symbol: " (name x))))))
|
a8a244dddaa921fd313d1ad8ddab3e8274bd2ad56a8a18cd5018f82343a8da06 | gvannest/piscine_OCaml | life.ml | type phosphate = string
type deoxyribose = string
type nucleobase = A | T | C | G | U | None
type nucleotide = {
phosphate : phosphate ;
deoxyribose : deoxyribose ;
nucleobase : nucleobase
}
type helix = nucleotide list
let generate_nucleotide c =
{
phosphate = "phosphate" ;
deoxyribose = "deoxyribose" ;
nucleobase = match c with
| 'A' -> A
| 'T' -> T
| 'C' -> C
| 'G' -> G
| 'U' -> U
| _ -> None
}
let generate_helix n =
if n < 1 then begin print_endline "Error: number of nucleotides must be greater than 0 to generate an helix" ; [] end
else begin
Random.self_init() ;
let rec choice = function
| 0 -> 'A'
| 1 -> 'T'
| 2 -> 'C'
| 3 -> 'G'
| _ -> 'O'
in
let rec gen_helix_aux i (acc: helix) = match i with
| y when y = n -> acc
| _ -> gen_helix_aux (i + 1) ((generate_nucleotide (choice (Random.int 4))) :: acc)
in
gen_helix_aux 0 []
end
type strOption = String of string | None
let extractStrOption value = match value with
| None -> "N/A"
| String str -> str
let nucleobase_str = function
| A -> String "A"
| T -> String "T"
| C -> String "C"
| G -> String "G"
| U -> String "U"
| _ -> None
let helix_to_string (lst: helix) =
let rec loop lst_remaining str = match lst_remaining with
| [] -> str
| h :: t -> begin
let nclbase = nucleobase_str h.nucleobase in
match nclbase with
| None -> loop t str
| _ -> loop t (str ^ (extractStrOption nclbase))
end
in
loop lst ""
let complementary_helix (helix:helix) =
let get_complement = function
| A -> 'T'
| T -> 'A'
| C -> 'G'
| G -> 'C'
| _ -> 'O'
in
let rec loop remaining_helix (comp_helix:helix) = match remaining_helix with
| [] -> comp_helix
| h :: t -> loop t (comp_helix@[generate_nucleotide (get_complement h.nucleobase)])
in
loop helix []
(* ----------------- ex06 ----------------- *)
type rna = nucleobase list
let generate_rna (hlx:helix) =
let compl_helix = complementary_helix hlx in
let rec loop input_compl_helix (rna:rna) = match input_compl_helix with
| [] -> rna
| h :: t when h.nucleobase = T -> loop t (rna@[U])
| h :: t -> loop t (rna@[h.nucleobase])
in loop compl_helix []
let print_rna (rna:rna) =
let rec loop rna_lst str = match rna_lst with
| [] -> str
| h :: t -> if t <> [] then loop t (str ^ (extractStrOption (nucleobase_str h)) ^ ", ") else loop t (str ^ (extractStrOption (nucleobase_str h)))
in print_char '[' ; print_string (loop rna "") ; print_string "]\n"
(* ----------------- ex07 ----------------- *)
let generate_bases_triplets (rna:rna) =
let rec create_triplets rna_lst output = match rna_lst with
| h :: a :: b :: tail -> create_triplets tail (output @ [(h, a, b)])
| _ -> output
in create_triplets rna []
let print_list_triplets lst =
print_char '[' ;
let rec loop new_lst = match new_lst with
| [] -> print_char ']' ; print_char '\n'
| h :: t -> match h with
| (a, b, c) -> begin
print_char '(' ; print_string (extractStrOption (nucleobase_str a)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str b)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str c)) ;
if t <> [] then print_string "), " else print_char ')';
loop t
end
in loop lst
type aminoacid = Ala | Arg | Asn | Asp | Cys | Gln | Glu | Gly | His | Ile | Leu | Lys | Met | Phe | Pro | Ser | Thr | Trp | Tyr | Val | Stop
type protein = aminoacid list
let string_of_protein (protein:protein) =
let string_of_aminoacid = function
| Ala -> "Alanine"
| Arg -> "Arginine"
| Asn -> "Asparagine"
| Asp -> "Aspatique"
| Cys -> "Cysteine"
| Gln -> "Glutamine"
| Glu -> "Glutamique"
| Gly -> "Glycine"
| His -> "Histidine"
| Ile -> "Isoleucine"
| Leu -> "Leucine"
| Lys -> "Lysine"
| Met -> "Methionine"
| Phe -> "Phenylalanine"
| Pro -> "Proline"
| Ser -> "Serine"
| Thr -> "Threonine"
| Trp -> "Tryptophane"
| Tyr -> "Tyrosine"
| Val -> "Valine"
| Stop -> "End of Translation"
in
let rec loop protein_loop output = match protein_loop with
| [] -> output
| h :: t -> if t <> [] then begin loop t (output ^ (string_of_aminoacid h) ^ ", ") end else begin output ^ (string_of_aminoacid h) end
in
loop protein ""
let decode_arn (rna:rna) =
let triplets = generate_bases_triplets rna in
let rec decode_aux rna_tripl_lst (protein:protein) = match rna_tripl_lst with
| (U,A,A) :: (U,A,G) :: (U,G,A) :: tail -> (protein@[Stop])
| (G,C,A) :: (G,C,C) :: (G,C,G) :: (G,C,U) :: tail -> decode_aux tail (protein@[Ala])
| (A,G,A) :: (A,G,G) :: (C,G,A) :: (C,G,C) :: (C,G,G) :: (C,G,U) :: tail -> decode_aux tail (protein@[Arg])
| (A,A,C) :: (A,A,U) :: tail -> decode_aux tail (protein@[Asn])
| (G,A,C) :: (G,A,U) :: tail -> decode_aux tail (protein@[Asp])
| (U,G,C) :: (U,G,U) :: tail -> decode_aux tail (protein@[Cys])
| (C,A,A) :: (C,A,G) :: tail -> decode_aux tail (protein@[Gln])
| (G,A,A) :: (G,A,G) :: tail -> decode_aux tail (protein@[Glu])
| (G,G,A) :: (G,G,C) :: (G,G,G) :: (G,G,U) :: tail -> decode_aux tail (protein@[Gly])
| (C,A,C) :: (C,A,U) :: tail -> decode_aux tail (protein@[His])
| (A,U,A) :: (A,U,C) :: (A,U,U) :: tail -> decode_aux tail (protein@[Ile])
| (C,U,A) :: (C,U,C) :: (C,U,G) :: (C,U,U) :: (U,U,A) :: (U,U,G) :: tail -> decode_aux tail (protein@[Leu])
| (A,A,A) :: (A,A,G) :: tail -> decode_aux tail (protein@[Lys])
| (A,U,G) :: tail -> decode_aux tail (protein@[Met])
| (U,U,C) :: (U,U,U) :: tail -> decode_aux tail (protein@[Phe])
| (C,C,C) :: (C,C,A) :: (C,C,G) :: (C,C,U) :: tail -> decode_aux tail (protein@[Pro])
| (U,C,A) :: (U,C,C) :: (U,C,G) :: (U,C,U) :: (A,G,U) :: (A,G,C) :: tail -> decode_aux tail (protein@[Ser])
| (A,C,A) :: (A,C,C) :: (A,C,G) :: (A,C,U) :: tail -> decode_aux tail (protein@[Thr])
| (U,G,G) :: tail -> decode_aux tail (protein@[Trp])
| (U,A,C) :: (U,A,U) :: tail -> decode_aux tail (protein@[Tyr])
| (G,U,A) :: (G,U,C) :: (G,U,G) :: (G,U,U) :: tail -> decode_aux tail (protein@[Val])
| h :: tail -> decode_aux tail protein
| [] -> protein
in decode_aux triplets []
(* ----------------- ex08 ----------------- *)
let print_helix hlx =
let str_of_nucleotide ncl = match ncl.nucleobase with
| A -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = A}"
| T -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = T}"
| C -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = C}"
| G -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = G}"
| U -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = U}"
| _ -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = None}"
in
let rec loop_in_hlx hlx_remaining str = match hlx_remaining with
| [] -> str
| h :: t -> if t <> [] then begin loop_in_hlx t (str ^ (str_of_nucleotide h) ^ ",\n") end else begin loop_in_hlx t (str ^ (str_of_nucleotide h)) end
in
print_endline "[" ; print_string (loop_in_hlx hlx "") ; print_endline "\n]"
let life str =
print_string "input : " ; print_endline str ; print_endline "------------" ;
let len = String.length str in
let rec helix_from_string idx (helix:helix) =
match idx with
| y when y = len -> helix
| _ -> helix_from_string (idx + 1) (helix @ [generate_nucleotide (String.get str idx)])
in
let hlx = helix_from_string 0 [] in begin print_endline "Associated helix : " ; print_helix hlx ; print_endline "------------" end;
let compl_hlx = complementary_helix hlx in begin print_endline "Complementary helix : " ; print_helix compl_hlx ; print_endline "------------" end;
let rna = generate_rna hlx in begin print_endline "RNA : " ; print_rna rna ; print_endline "------------" end;
let triplets = generate_bases_triplets rna in begin print_endline "List of triplets : " ; print_list_triplets triplets ; print_endline "------------" end;
let decoded_arn = decode_arn rna in
begin
print_endline "Decoded arn: " ;
decoded_arn
end
let () =
print_endline (string_of_protein (life "TTGTTACTTCTCTATTAGTAAATTATCACT")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "ACC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAA")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAATACTTTTTC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAATACATTATCACTTTTTTC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "GGGGGTGGCGGAAAGAAATACATTATCACTTTTTTC")) ;
| null | https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d02/ex08/life.ml | ocaml | ----------------- ex06 -----------------
----------------- ex07 -----------------
----------------- ex08 ----------------- | type phosphate = string
type deoxyribose = string
type nucleobase = A | T | C | G | U | None
type nucleotide = {
phosphate : phosphate ;
deoxyribose : deoxyribose ;
nucleobase : nucleobase
}
type helix = nucleotide list
let generate_nucleotide c =
{
phosphate = "phosphate" ;
deoxyribose = "deoxyribose" ;
nucleobase = match c with
| 'A' -> A
| 'T' -> T
| 'C' -> C
| 'G' -> G
| 'U' -> U
| _ -> None
}
let generate_helix n =
if n < 1 then begin print_endline "Error: number of nucleotides must be greater than 0 to generate an helix" ; [] end
else begin
Random.self_init() ;
let rec choice = function
| 0 -> 'A'
| 1 -> 'T'
| 2 -> 'C'
| 3 -> 'G'
| _ -> 'O'
in
let rec gen_helix_aux i (acc: helix) = match i with
| y when y = n -> acc
| _ -> gen_helix_aux (i + 1) ((generate_nucleotide (choice (Random.int 4))) :: acc)
in
gen_helix_aux 0 []
end
type strOption = String of string | None
let extractStrOption value = match value with
| None -> "N/A"
| String str -> str
let nucleobase_str = function
| A -> String "A"
| T -> String "T"
| C -> String "C"
| G -> String "G"
| U -> String "U"
| _ -> None
let helix_to_string (lst: helix) =
let rec loop lst_remaining str = match lst_remaining with
| [] -> str
| h :: t -> begin
let nclbase = nucleobase_str h.nucleobase in
match nclbase with
| None -> loop t str
| _ -> loop t (str ^ (extractStrOption nclbase))
end
in
loop lst ""
let complementary_helix (helix:helix) =
let get_complement = function
| A -> 'T'
| T -> 'A'
| C -> 'G'
| G -> 'C'
| _ -> 'O'
in
let rec loop remaining_helix (comp_helix:helix) = match remaining_helix with
| [] -> comp_helix
| h :: t -> loop t (comp_helix@[generate_nucleotide (get_complement h.nucleobase)])
in
loop helix []
type rna = nucleobase list
let generate_rna (hlx:helix) =
let compl_helix = complementary_helix hlx in
let rec loop input_compl_helix (rna:rna) = match input_compl_helix with
| [] -> rna
| h :: t when h.nucleobase = T -> loop t (rna@[U])
| h :: t -> loop t (rna@[h.nucleobase])
in loop compl_helix []
let print_rna (rna:rna) =
let rec loop rna_lst str = match rna_lst with
| [] -> str
| h :: t -> if t <> [] then loop t (str ^ (extractStrOption (nucleobase_str h)) ^ ", ") else loop t (str ^ (extractStrOption (nucleobase_str h)))
in print_char '[' ; print_string (loop rna "") ; print_string "]\n"
let generate_bases_triplets (rna:rna) =
let rec create_triplets rna_lst output = match rna_lst with
| h :: a :: b :: tail -> create_triplets tail (output @ [(h, a, b)])
| _ -> output
in create_triplets rna []
let print_list_triplets lst =
print_char '[' ;
let rec loop new_lst = match new_lst with
| [] -> print_char ']' ; print_char '\n'
| h :: t -> match h with
| (a, b, c) -> begin
print_char '(' ; print_string (extractStrOption (nucleobase_str a)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str b)) ;
print_string ", ";
print_string (extractStrOption (nucleobase_str c)) ;
if t <> [] then print_string "), " else print_char ')';
loop t
end
in loop lst
type aminoacid = Ala | Arg | Asn | Asp | Cys | Gln | Glu | Gly | His | Ile | Leu | Lys | Met | Phe | Pro | Ser | Thr | Trp | Tyr | Val | Stop
type protein = aminoacid list
let string_of_protein (protein:protein) =
let string_of_aminoacid = function
| Ala -> "Alanine"
| Arg -> "Arginine"
| Asn -> "Asparagine"
| Asp -> "Aspatique"
| Cys -> "Cysteine"
| Gln -> "Glutamine"
| Glu -> "Glutamique"
| Gly -> "Glycine"
| His -> "Histidine"
| Ile -> "Isoleucine"
| Leu -> "Leucine"
| Lys -> "Lysine"
| Met -> "Methionine"
| Phe -> "Phenylalanine"
| Pro -> "Proline"
| Ser -> "Serine"
| Thr -> "Threonine"
| Trp -> "Tryptophane"
| Tyr -> "Tyrosine"
| Val -> "Valine"
| Stop -> "End of Translation"
in
let rec loop protein_loop output = match protein_loop with
| [] -> output
| h :: t -> if t <> [] then begin loop t (output ^ (string_of_aminoacid h) ^ ", ") end else begin output ^ (string_of_aminoacid h) end
in
loop protein ""
let decode_arn (rna:rna) =
let triplets = generate_bases_triplets rna in
let rec decode_aux rna_tripl_lst (protein:protein) = match rna_tripl_lst with
| (U,A,A) :: (U,A,G) :: (U,G,A) :: tail -> (protein@[Stop])
| (G,C,A) :: (G,C,C) :: (G,C,G) :: (G,C,U) :: tail -> decode_aux tail (protein@[Ala])
| (A,G,A) :: (A,G,G) :: (C,G,A) :: (C,G,C) :: (C,G,G) :: (C,G,U) :: tail -> decode_aux tail (protein@[Arg])
| (A,A,C) :: (A,A,U) :: tail -> decode_aux tail (protein@[Asn])
| (G,A,C) :: (G,A,U) :: tail -> decode_aux tail (protein@[Asp])
| (U,G,C) :: (U,G,U) :: tail -> decode_aux tail (protein@[Cys])
| (C,A,A) :: (C,A,G) :: tail -> decode_aux tail (protein@[Gln])
| (G,A,A) :: (G,A,G) :: tail -> decode_aux tail (protein@[Glu])
| (G,G,A) :: (G,G,C) :: (G,G,G) :: (G,G,U) :: tail -> decode_aux tail (protein@[Gly])
| (C,A,C) :: (C,A,U) :: tail -> decode_aux tail (protein@[His])
| (A,U,A) :: (A,U,C) :: (A,U,U) :: tail -> decode_aux tail (protein@[Ile])
| (C,U,A) :: (C,U,C) :: (C,U,G) :: (C,U,U) :: (U,U,A) :: (U,U,G) :: tail -> decode_aux tail (protein@[Leu])
| (A,A,A) :: (A,A,G) :: tail -> decode_aux tail (protein@[Lys])
| (A,U,G) :: tail -> decode_aux tail (protein@[Met])
| (U,U,C) :: (U,U,U) :: tail -> decode_aux tail (protein@[Phe])
| (C,C,C) :: (C,C,A) :: (C,C,G) :: (C,C,U) :: tail -> decode_aux tail (protein@[Pro])
| (U,C,A) :: (U,C,C) :: (U,C,G) :: (U,C,U) :: (A,G,U) :: (A,G,C) :: tail -> decode_aux tail (protein@[Ser])
| (A,C,A) :: (A,C,C) :: (A,C,G) :: (A,C,U) :: tail -> decode_aux tail (protein@[Thr])
| (U,G,G) :: tail -> decode_aux tail (protein@[Trp])
| (U,A,C) :: (U,A,U) :: tail -> decode_aux tail (protein@[Tyr])
| (G,U,A) :: (G,U,C) :: (G,U,G) :: (G,U,U) :: tail -> decode_aux tail (protein@[Val])
| h :: tail -> decode_aux tail protein
| [] -> protein
in decode_aux triplets []
let print_helix hlx =
let str_of_nucleotide ncl = match ncl.nucleobase with
| A -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = A}"
| T -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = T}"
| C -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = C}"
| G -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = G}"
| U -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = U}"
| _ -> "{phosphate = \"phosphate\" ; deoxyribose = \"deoxyribose\" ; nucleobase = None}"
in
let rec loop_in_hlx hlx_remaining str = match hlx_remaining with
| [] -> str
| h :: t -> if t <> [] then begin loop_in_hlx t (str ^ (str_of_nucleotide h) ^ ",\n") end else begin loop_in_hlx t (str ^ (str_of_nucleotide h)) end
in
print_endline "[" ; print_string (loop_in_hlx hlx "") ; print_endline "\n]"
let life str =
print_string "input : " ; print_endline str ; print_endline "------------" ;
let len = String.length str in
let rec helix_from_string idx (helix:helix) =
match idx with
| y when y = len -> helix
| _ -> helix_from_string (idx + 1) (helix @ [generate_nucleotide (String.get str idx)])
in
let hlx = helix_from_string 0 [] in begin print_endline "Associated helix : " ; print_helix hlx ; print_endline "------------" end;
let compl_hlx = complementary_helix hlx in begin print_endline "Complementary helix : " ; print_helix compl_hlx ; print_endline "------------" end;
let rna = generate_rna hlx in begin print_endline "RNA : " ; print_rna rna ; print_endline "------------" end;
let triplets = generate_bases_triplets rna in begin print_endline "List of triplets : " ; print_list_triplets triplets ; print_endline "------------" end;
let decoded_arn = decode_arn rna in
begin
print_endline "Decoded arn: " ;
decoded_arn
end
let () =
print_endline (string_of_protein (life "TTGTTACTTCTCTATTAGTAAATTATCACT")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "ACC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAA")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAATACTTTTTC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "AAGAAATACATTATCACTTTTTTC")) ;
print_endline "\n********************\n" ;
print_endline (string_of_protein (life "GGGGGTGGCGGAAAGAAATACATTATCACTTTTTTC")) ;
|
ecdd55f865be591850e550df434ea2cffac0d427d16c8a019d132774b25054c4 | nineties-retro/sps | bootstrap-scm.scm | ;
Loads all the required files that make up the Pre - Scheme to GNU C compiler
; into scm and runs the compiler on the file pre-scheme-compiler.scm.
;
(load "scm/sps-if.scm")
(load "scm/sps-assert.scm")
(load "scm/sps-byte-vector.scm")
(load "sps-byte-vector.scm")
(load "scm/sps-strings-scm.scm")
;;(load "scm/sps-strings-sps.scm")
;(load "sps/sps-word.scm")
;(load "sps/sps-compat.scm")
;(load "sps/sps-io.scm")
;(load "sps/sps-mem.scm")
;(load "sps/sps-mem-fsp.scm")
;(load "sps/sps-mem-sp.scm")
(load "scm/sps-word.scm")
(load "scm/sps-compat.scm")
(load "scm/sps-io.scm")
(load "scm/sps-mem.scm")
(load "scm/sps-mem-fsp.scm")
(load "scm/sps-mem-sp.scm")
(load "sps-char-map.scm")
(load "sps-input.scm")
(define *pools* (sps:mem:pools:open))
(define *sp* (sps:mem:sp:open *pools*))
;(define *sp-alloc* (sps:mem:pool:alloc sps:mem:sp:ops))
;(define *sp-free* (sps:mem:pool:free sps:mem:sp:ops))
;(define *sp-close* (sps:mem:pool:close sps:mem:sp:ops))
(load "sps-input-file.scm")
(define *input-file-name* (sps:static-string "pre-scheme-compiler.scm"))
(define *input-file* (sps:make-static-vector sps:input:file:size))
(define *input-ok* (sps:input:file:open *input-file* *input-file-name*
*sp* sps:mem:sp:ops))
(load "sps-lexer-action.scm")
(load "sps-lexer-error.scm")
(load "sps-lexer.scm")
;(load "sps-pp.scm")
;(load "sps-pp-direct.scm")
(define *lexer* (sps:make-static-vector sps:lexer:size))
;;(sps:lexer:open *lexer* *input-file* sps:input:file:ops sps:pp::errors)
;;(sps:lexer:lex *lexer* sps:pp::actions #t)
(load "sps-strings-scm.scm")
;;(load "sps-strings-sps.scm")
(load "sps-hash.scm")
(load "sps-hash-table.scm")
(define *hash-table* (sps:make-static-vector sps:hash-table:size))
(define *hash-table-ok* (sps:hash-table:open *hash-table* *pools*))
(load "sps-ast.scm")
(define *ast* (sps:make-static-vector sps:ast::state:size))
(define *ast-ok* (sps:ast::state-open *ast* *pools* *hash-table*))
(sps:lexer:open *lexer* *input-file* sps:input:file:ops sps:ast::errors)
;;(load "sps-ast-pp.scm")
;;(sps:ast-pp (sps:ast::state:root (sps:ast *lexer* *ast*)) 0)
(load "sps-symbol-table.scm")
(define *symbol-table* (sps:make-static-vector sps:symbol-table:size))
(sps:symbol-table:open *symbol-table* *pools*)
(define *preamble-file-name* (sps:static-string "bootstrap_preamble.c"))
(define *main-file-name* (sps:static-string "bootstrap.c"))
(define *preamble-port* (sps:io:open-output *preamble-file-name*))
(define *main-port* (sps:io:open-output *main-file-name*))
(load "sps-to-c.scm")
(sps:io:print:string *main-port* "#include \"sps_prelude.h\"\n")
(sps:io:print:string *main-port* "#include \"bootstrap_preamble.c\"\n")
(define *sps->c* (sps:make-static-vector sps->c:state:size))
(define *sp->c-ok* (sps->c:state:open *sps->c* *pools* *hash-table*
*symbol-table*
*main-port* *preamble-port*))
(define *ast-ok* (sps:ast *lexer* *ast*))
(sps:or *ast-ok* (begin (display "problem building AST") (newline)))
(sps->c *sps->c* (sps:ast::state:root *ast*))
(close-port *main-port*)
(close-port *preamble-port*)
| null | https://raw.githubusercontent.com/nineties-retro/sps/bf15b415f4cdf5d6d69ae2f39c250db2090c0817/bootstrap-scm.scm | scheme |
into scm and runs the compiler on the file pre-scheme-compiler.scm.
(load "scm/sps-strings-sps.scm")
(load "sps/sps-word.scm")
(load "sps/sps-compat.scm")
(load "sps/sps-io.scm")
(load "sps/sps-mem.scm")
(load "sps/sps-mem-fsp.scm")
(load "sps/sps-mem-sp.scm")
(define *sp-alloc* (sps:mem:pool:alloc sps:mem:sp:ops))
(define *sp-free* (sps:mem:pool:free sps:mem:sp:ops))
(define *sp-close* (sps:mem:pool:close sps:mem:sp:ops))
(load "sps-pp.scm")
(load "sps-pp-direct.scm")
(sps:lexer:open *lexer* *input-file* sps:input:file:ops sps:pp::errors)
(sps:lexer:lex *lexer* sps:pp::actions #t)
(load "sps-strings-sps.scm")
(load "sps-ast-pp.scm")
(sps:ast-pp (sps:ast::state:root (sps:ast *lexer* *ast*)) 0) | Loads all the required files that make up the Pre - Scheme to GNU C compiler
(load "scm/sps-if.scm")
(load "scm/sps-assert.scm")
(load "scm/sps-byte-vector.scm")
(load "sps-byte-vector.scm")
(load "scm/sps-strings-scm.scm")
(load "scm/sps-word.scm")
(load "scm/sps-compat.scm")
(load "scm/sps-io.scm")
(load "scm/sps-mem.scm")
(load "scm/sps-mem-fsp.scm")
(load "scm/sps-mem-sp.scm")
(load "sps-char-map.scm")
(load "sps-input.scm")
(define *pools* (sps:mem:pools:open))
(define *sp* (sps:mem:sp:open *pools*))
(load "sps-input-file.scm")
(define *input-file-name* (sps:static-string "pre-scheme-compiler.scm"))
(define *input-file* (sps:make-static-vector sps:input:file:size))
(define *input-ok* (sps:input:file:open *input-file* *input-file-name*
*sp* sps:mem:sp:ops))
(load "sps-lexer-action.scm")
(load "sps-lexer-error.scm")
(load "sps-lexer.scm")
(define *lexer* (sps:make-static-vector sps:lexer:size))
(load "sps-strings-scm.scm")
(load "sps-hash.scm")
(load "sps-hash-table.scm")
(define *hash-table* (sps:make-static-vector sps:hash-table:size))
(define *hash-table-ok* (sps:hash-table:open *hash-table* *pools*))
(load "sps-ast.scm")
(define *ast* (sps:make-static-vector sps:ast::state:size))
(define *ast-ok* (sps:ast::state-open *ast* *pools* *hash-table*))
(sps:lexer:open *lexer* *input-file* sps:input:file:ops sps:ast::errors)
(load "sps-symbol-table.scm")
(define *symbol-table* (sps:make-static-vector sps:symbol-table:size))
(sps:symbol-table:open *symbol-table* *pools*)
(define *preamble-file-name* (sps:static-string "bootstrap_preamble.c"))
(define *main-file-name* (sps:static-string "bootstrap.c"))
(define *preamble-port* (sps:io:open-output *preamble-file-name*))
(define *main-port* (sps:io:open-output *main-file-name*))
(load "sps-to-c.scm")
(sps:io:print:string *main-port* "#include \"sps_prelude.h\"\n")
(sps:io:print:string *main-port* "#include \"bootstrap_preamble.c\"\n")
(define *sps->c* (sps:make-static-vector sps->c:state:size))
(define *sp->c-ok* (sps->c:state:open *sps->c* *pools* *hash-table*
*symbol-table*
*main-port* *preamble-port*))
(define *ast-ok* (sps:ast *lexer* *ast*))
(sps:or *ast-ok* (begin (display "problem building AST") (newline)))
(sps->c *sps->c* (sps:ast::state:root *ast*))
(close-port *main-port*)
(close-port *preamble-port*)
|
e6ec0c74159dcc668ba2ee1bf2f9cc6cc3fea26a5fdf8f93951ffd140cc74dda | daypack-dev/daypack-lib | time_slots.ml | open Int64_utils
exception Time_slots_are_not_sorted
exception Time_slots_are_not_disjoint
module Check = struct
let check_if_valid (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.map Time_slot.Check.check_if_valid time_slots
let check_if_not_empty (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.map Time_slot.Check.check_if_not_empty time_slots
let check_if_sorted (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors ~f:Time_slot.le
~f_exn:(fun _ _ -> Time_slots_are_not_sorted)
time_slots
let check_if_sorted_rev (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors ~f:Time_slot.ge
~f_exn:(fun _ _ -> Time_slots_are_not_sorted)
time_slots
let check_if_disjoint (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors
~f:(fun x y ->
match Time_slot.overlap_of_a_over_b ~a:y ~b:x with
| None, None, None | Some _, None, None | None, None, Some _ -> true
| _ -> false)
~f_exn:(fun _ _ -> Time_slots_are_not_disjoint)
time_slots
let check_if_normalized (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
time_slots
|> check_if_valid
|> check_if_not_empty
|> check_if_sorted
|> check_if_disjoint
end
module Filter = struct
let filter_invalid (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.filter Time_slot.Check.is_valid time_slots
let filter_invalid_list (time_slots : Time_slot.t list) : Time_slot.t list =
List.filter Time_slot.Check.is_valid time_slots
let filter_empty (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.filter Time_slot.Check.is_not_empty time_slots
let filter_empty_list (time_slots : Time_slot.t list) : Time_slot.t list =
List.filter Time_slot.Check.is_not_empty time_slots
end
module Sort = struct
let sort_time_slots_list ?(skip_check = false) (time_slots : Time_slot.t list)
: Time_slot.t list =
time_slots
|> (fun l ->
if skip_check then l
else l |> List.to_seq |> Check.check_if_valid |> List.of_seq)
|> List.sort Time_slot.compare
let sort_uniq_time_slots_list ?(skip_check = false)
(time_slots : Time_slot.t list) : Time_slot.t list =
time_slots
|> (fun l ->
if skip_check then l
else l |> List.to_seq |> Check.check_if_valid |> List.of_seq)
|> List.sort_uniq Time_slot.compare
let sort_uniq_time_slots ?(skip_check = false)
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> List.of_seq
|> List.sort_uniq Time_slot.compare
|> List.to_seq
let sort_time_slots ?(skip_check = false) (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> List.of_seq
|> List.sort Time_slot.compare
|> List.to_seq
end
module Join_internal = struct
let join (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux cur time_slots =
match time_slots () with
| Seq.Nil -> (
match cur with None -> Seq.empty | Some x -> Seq.return x )
| Seq.Cons ((start, end_exc), rest) -> (
match cur with
| None -> aux (Some (start, end_exc)) rest
| Some cur -> (
match Time_slot.join cur (start, end_exc) with
| Some x -> aux (Some x) rest
| None ->
(* cannot be merged, add time slot being carried to the sequence *)
fun () -> Seq.Cons (cur, aux (Some (start, end_exc)) rest) ) )
in
aux None time_slots
end
let join ?(skip_check = false) time_slots =
time_slots
|> (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> Join_internal.join
module Normalize = struct
let normalize ?(skip_filter_invalid = false) ?(skip_filter_empty = false)
?(skip_sort = false) time_slots =
time_slots
|> (fun s -> if skip_filter_invalid then s else Filter.filter_invalid s)
|> (fun s -> if skip_filter_empty then s else Filter.filter_empty s)
|> (fun s -> if skip_sort then s else Sort.sort_uniq_time_slots s)
|> Join_internal.join
let normalize_list_in_seq_out ?(skip_filter_invalid = false)
?(skip_filter_empty = false) ?(skip_sort = false) time_slots =
time_slots
|> List.to_seq
|> normalize ~skip_filter_invalid ~skip_filter_empty ~skip_sort
end
module Slice_internal = struct
let slice_start ~start (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux start time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), rest) ->
if start <= ts_start then
(* entire time slot is after start, do nothing *)
time_slots
else if ts_start < start && start < ts_end_exc then
(* time slot spans across the start mark, split time slot *)
fun () -> Seq.Cons ((start, ts_end_exc), rest)
else
(* time slot is before start mark, move to next time slot *)
aux start rest
in
aux start time_slots
let slice_end_exc ~end_exc (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
let rec aux end_exc time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), rest) ->
if end_exc <= ts_start then
(* entire time slot is after end_exc mark, drop everything *)
aux end_exc Seq.empty
else if ts_start < end_exc && end_exc < ts_end_exc then
(* time slot spans across the end_exc mark, split time slot,
skip remaining slots *)
fun () -> Seq.Cons ((ts_start, end_exc), aux end_exc Seq.empty)
else
(* time slot is before end_exc, add to sequence and move to next time slot *)
fun () -> Seq.Cons ((ts_start, ts_end_exc), aux end_exc rest)
in
aux end_exc time_slots
end
module Slice_rev_internal = struct
let slice_start ~start (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux acc start time_slots =
match time_slots () with
| Seq.Nil -> List.rev acc |> List.to_seq
| Seq.Cons ((ts_start, ts_end_exc), slots) ->
if start <= ts_start then
entire time slot is after start , add to acc
aux ((ts_start, ts_end_exc) :: acc) start slots
else if ts_start < start && start < ts_end_exc then
(* time slot spans across the start mark, split time slot *)
aux ((start, ts_end_exc) :: acc) start slots
else
(* time slot is before start mark, do nothing *)
aux acc start Seq.empty
in
aux [] start time_slots
let slice_end_exc ~end_exc (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
let rec aux end_exc time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), slots) ->
if ts_end_exc <= end_exc then
(* entire time slot is before end_exc mark, do nothing *)
time_slots
else if ts_start < end_exc && end_exc < ts_end_exc then
(* time slot spans across the end_exc mark, split time slot *)
OSeq.cons (ts_start, end_exc) slots
else
(* time slot is after end_exc mark, move to next time slot *)
aux end_exc slots
in
aux end_exc time_slots
end
module Slice = struct
let slice ?(skip_check = false) ?start ?end_exc time_slots =
time_slots
|> (fun s ->
if skip_check then s
else
s
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted)
|> (fun s ->
match start with
| None -> s
| Some start -> Slice_internal.slice_start ~start s)
|> fun s ->
match end_exc with
| None -> s
| Some end_exc -> Slice_internal.slice_end_exc ~end_exc s
let slice_rev ?(skip_check = false) ?start ?end_exc time_slots =
time_slots
|> (fun s ->
if skip_check then s
else
s
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted_rev)
|> (fun s ->
match start with
| None -> s
| Some start -> Slice_rev_internal.slice_start ~start s)
|> fun s ->
match end_exc with
| None -> s
| Some end_exc -> Slice_rev_internal.slice_end_exc ~end_exc s
end
let relative_complement ?(skip_check = false) ~(not_mem_of : Time_slot.t Seq.t)
(mem_of : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux mem_of not_mem_of =
match (mem_of (), not_mem_of ()) with
| Seq.Nil, _ -> Seq.empty
| _, Seq.Nil -> mem_of
| ( Seq.Cons (mem_of_ts, mem_of_rest),
Seq.Cons (not_mem_of_ts, not_mem_of_rest) ) -> (
let mem_of () = Seq.Cons (mem_of_ts, mem_of_rest) in
let not_mem_of () = Seq.Cons (not_mem_of_ts, not_mem_of_rest) in
match Time_slot.overlap_of_a_over_b ~a:mem_of_ts ~b:not_mem_of_ts with
| None, None, None ->
mem_of_ts is empty , drop mem_of_ts
aux mem_of_rest not_mem_of
| Some _, None, None ->
mem_of_ts is before not_mem_of_ts entirely , output mem_of
fun () -> Seq.Cons (mem_of_ts, aux mem_of_rest not_mem_of)
| None, None, Some _ ->
(* not_mem_of_ts is before mem_of entirely, drop not_mem_of_ts *)
aux mem_of not_mem_of_rest
| Some (start, end_exc), Some _, None ->
fun () -> Seq.Cons ((start, end_exc), aux mem_of_rest not_mem_of)
| None, Some _, None -> aux mem_of_rest not_mem_of
| None, Some _, Some (start, end_exc) ->
let mem_of () = Seq.Cons ((start, end_exc), mem_of_rest) in
aux mem_of not_mem_of_rest
| Some (start1, end_exc1), _, Some (start2, end_exc2) ->
let mem_of () = Seq.Cons ((start2, end_exc2), mem_of_rest) in
fun () -> Seq.Cons ((start1, end_exc1), aux mem_of not_mem_of_rest)
)
in
let mem_of =
if skip_check then mem_of
else
mem_of
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let not_mem_of =
if skip_check then not_mem_of
else
not_mem_of
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
aux mem_of not_mem_of
let invert ?(skip_check = false) ~start ~end_exc
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
relative_complement ~skip_check ~not_mem_of:time_slots
(Seq.return (start, end_exc))
let inter ?(skip_check = false) (time_slots1 : Time_slot.t Seq.t)
(time_slots2 : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots1 time_slots2 : Time_slot.t Seq.t =
match (time_slots1 (), time_slots2 ()) with
| Seq.Nil, _ -> Seq.empty
| _, Seq.Nil -> Seq.empty
| Seq.Cons ((start1, end_exc1), rest1), Seq.Cons ((start2, end_exc2), rest2)
->
if end_exc1 < start2 then
1 is before 2 entirely , drop 1 , keep 2
aux rest1 time_slots2
else if end_exc2 < start1 then
2 is before 1 entirely , keep 1 , drop 2
aux time_slots1 rest2
else
(* there is an overlap or touching *)
let overlap_start = max start1 start2 in
let overlap_end_exc = min end_exc1 end_exc2 in
let s1 = if end_exc1 <= overlap_end_exc then rest1 else time_slots1 in
let s2 = if end_exc2 <= overlap_end_exc then rest2 else time_slots2 in
if overlap_start < overlap_end_exc then
(* there is an overlap *)
fun () -> Seq.Cons ((overlap_start, overlap_end_exc), aux s1 s2)
else aux s1 s2
in
let time_slots1 =
if skip_check then time_slots1
else
time_slots1
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else
time_slots2
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
aux time_slots1 time_slots2
module Merge = struct
let merge ?(skip_check = false) (time_slots1 : Time_slot.t Seq.t)
(time_slots2 : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots1 time_slots2 =
match (time_slots1 (), time_slots2 ()) with
| Seq.Nil, s | s, Seq.Nil -> fun () -> s
| Seq.Cons (x1, rest1), Seq.Cons (x2, rest2) ->
let ts1 () = Seq.Cons (x1, rest1) in
let ts2 () = Seq.Cons (x2, rest2) in
if Time_slot.le x1 x2 then fun () -> Seq.Cons (x1, aux rest1 ts2)
else fun () -> Seq.Cons (x2, aux rest2 ts1)
in
let time_slots1 =
if skip_check then time_slots1
else time_slots1 |> Check.check_if_valid |> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else time_slots2 |> Check.check_if_valid |> Check.check_if_sorted
in
aux time_slots1 time_slots2
let merge_multi_seq ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
Seq.fold_left
(fun acc time_slots -> merge ~skip_check acc time_slots)
Seq.empty time_slot_batches
let merge_multi_list ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
List.to_seq time_slot_batches |> merge_multi_seq ~skip_check
end
module Round_robin = struct
let collect_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t list) : Time_slot.t option list Seq.t =
batches
|> List.map (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> Seq_utils.collect_round_robin Time_slot.le
let merge_multi_list_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
collect_round_robin_non_decreasing ~skip_check batches
|> Seq.flat_map (fun l -> List.to_seq l |> Seq.filter_map (fun x -> x))
let merge_multi_seq_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
batches
|> List.of_seq
|> merge_multi_list_round_robin_non_decreasing ~skip_check
end
module Union = struct
let union ?(skip_check = false) time_slots1 time_slots2 =
let time_slots1 =
if skip_check then time_slots1
else
time_slots1
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else
time_slots2
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
Merge.merge time_slots1 time_slots2
|> Normalize.normalize ~skip_filter_invalid:true ~skip_filter_empty:true
~skip_sort:true
let union_multi_seq ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
Seq.fold_left
(fun acc time_slots -> union ~skip_check acc time_slots)
Seq.empty time_slot_batches
let union_multi_list ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
List.to_seq time_slot_batches |> union_multi_seq ~skip_check
end
let chunk ?(skip_check = false) ?(drop_partial = false) ~chunk_size
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((start, end_exc), rest) ->
let chunk_end_exc = min end_exc (start +^ chunk_size) in
let size = chunk_end_exc -^ start in
if size = 0L || (size < chunk_size && drop_partial) then aux rest
else
let rest () = Seq.Cons ((chunk_end_exc, end_exc), rest) in
fun () -> Seq.Cons ((start, chunk_end_exc), aux rest)
in
time_slots
|> (fun s -> if skip_check then s else s |> Check.check_if_valid)
|> aux
module Sum = struct
let sum_length ?(skip_check = false) (time_slots : Time_slot.t Seq.t) : int64
=
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> Seq.fold_left (fun acc (start, end_exc) -> acc +^ (end_exc -^ start)) 0L
let sum_length_list ?(skip_check = false) (time_slots : Time_slot.t list) :
int64 =
time_slots |> List.to_seq |> sum_length ~skip_check
end
module Bound = struct
let min_start_and_max_end_exc ?(skip_check = false)
(time_slots : Time_slot.t Seq.t) : (int64 * int64) option =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> Seq.fold_left
(fun acc (start, end_exc) ->
match acc with
| None -> Some (start, end_exc)
| Some (min_start, max_end_exc) ->
Some (min min_start start, max max_end_exc end_exc))
None
let min_start_and_max_end_exc_list ?(skip_check = false)
(time_slots : Time_slot.t list) : (int64 * int64) option =
time_slots |> List.to_seq |> min_start_and_max_end_exc ~skip_check
end
let shift_list ~offset (time_slots : Time_slot.t list) : Time_slot.t list =
List.map
(fun (start, end_exc) -> (start +^ offset, end_exc +^ offset))
time_slots
let equal (time_slots1 : Time_slot.t list) (time_slots2 : Time_slot.t list) :
bool =
let time_slots1 =
time_slots1 |> List.to_seq |> Normalize.normalize |> List.of_seq
in
let time_slots2 =
time_slots2 |> List.to_seq |> Normalize.normalize |> List.of_seq
in
time_slots1 = time_slots2
let a_is_subset_of_b ~(a : Time_slot.t Seq.t) ~(b : Time_slot.t Seq.t) : bool =
let inter = inter a b |> List.of_seq in
let a = List.of_seq a in
a = inter
let count_overlap ?(skip_check = false) (time_slots : Time_slot.t Seq.t) :
(Time_slot.t * int) Seq.t =
let flatten_buffer buffer =
buffer
|> List.sort (fun (x, _count) (y, _count) -> Time_slot.compare x y)
|> List.to_seq
|> Seq.flat_map (fun (x, count) ->
OSeq.(0 --^ count) |> Seq.map (fun _ -> x))
in
let flush_buffer_to_input buffer time_slots =
Merge.merge (flatten_buffer buffer) time_slots
in
let rec aux (cur : ((int64 * int64) * int) option)
(buffer : ((int64 * int64) * int) list) (time_slots : Time_slot.t Seq.t) :
(Time_slot.t * int) Seq.t =
match time_slots () with
| Seq.Nil -> (
match buffer with
| [] -> (
match cur with None -> Seq.empty | Some cur -> Seq.return cur )
| buffer -> aux cur [] (flatten_buffer buffer) )
| Seq.Cons (x, rest) -> (
let s () = Seq.Cons (x, rest) in
match cur with
| None -> (
match buffer with
| [] -> aux (Some (x, 1)) [] rest
| buffer -> aux None [] (flush_buffer_to_input buffer s) )
| Some ((cur_start, cur_end_exc), cur_count) -> (
match
Time_slot.overlap_of_a_over_b ~a:x ~b:(cur_start, cur_end_exc)
with
| None, None, None -> aux cur buffer rest
| Some _, _, _ ->
failwith "Unexpected case, time slots are not sorted"
(* raise (Invalid_argument "Time slots are not sorted") *)
| None, Some (start, end_exc), None
| None, Some (start, _), Some (_, end_exc) ->
if start = cur_start then
if end_exc < cur_end_exc then
failwith "Unexpected case, time slots are not sorted"
(* raise (Invalid_argument "Time slots are not sorted") *)
else if end_exc = cur_end_exc then
aux
(Some ((cur_start, cur_end_exc), succ cur_count))
buffer rest
else
aux
(Some ((cur_start, cur_end_exc), succ cur_count))
(((cur_end_exc, end_exc), 1) :: buffer)
rest
else fun () ->
Seq.Cons
( ((cur_start, start), cur_count),
let buffer =
if end_exc < cur_end_exc then
((start, end_exc), succ cur_count)
:: ((end_exc, cur_end_exc), cur_count)
:: buffer
else if end_exc = cur_end_exc then
((start, cur_end_exc), succ cur_count) :: buffer
else
((start, cur_end_exc), succ cur_count)
:: ((cur_end_exc, end_exc), 1)
:: buffer
in
aux None buffer rest )
| None, None, Some _ ->
fun () ->
Seq.Cons
(((cur_start, cur_end_exc), cur_count), aux None buffer s) )
)
in
time_slots
|> (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> aux None []
module Serialize = struct
let pack_time_slots time_slots =
List.map Time_slot.Serialize.pack_time_slot time_slots
end
module Deserialize = struct
let unpack_time_slots time_slots =
List.map Time_slot.Deserialize.unpack_time_slot time_slots
end
| null | https://raw.githubusercontent.com/daypack-dev/daypack-lib/63fa5d85007eca73aa6c51874a839636dd0403d3/src/time_slots.ml | ocaml | cannot be merged, add time slot being carried to the sequence
entire time slot is after start, do nothing
time slot spans across the start mark, split time slot
time slot is before start mark, move to next time slot
entire time slot is after end_exc mark, drop everything
time slot spans across the end_exc mark, split time slot,
skip remaining slots
time slot is before end_exc, add to sequence and move to next time slot
time slot spans across the start mark, split time slot
time slot is before start mark, do nothing
entire time slot is before end_exc mark, do nothing
time slot spans across the end_exc mark, split time slot
time slot is after end_exc mark, move to next time slot
not_mem_of_ts is before mem_of entirely, drop not_mem_of_ts
there is an overlap or touching
there is an overlap
raise (Invalid_argument "Time slots are not sorted")
raise (Invalid_argument "Time slots are not sorted") | open Int64_utils
exception Time_slots_are_not_sorted
exception Time_slots_are_not_disjoint
module Check = struct
let check_if_valid (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.map Time_slot.Check.check_if_valid time_slots
let check_if_not_empty (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.map Time_slot.Check.check_if_not_empty time_slots
let check_if_sorted (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors ~f:Time_slot.le
~f_exn:(fun _ _ -> Time_slots_are_not_sorted)
time_slots
let check_if_sorted_rev (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors ~f:Time_slot.ge
~f_exn:(fun _ _ -> Time_slots_are_not_sorted)
time_slots
let check_if_disjoint (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq_utils.check_if_f_holds_for_immediate_neighbors
~f:(fun x y ->
match Time_slot.overlap_of_a_over_b ~a:y ~b:x with
| None, None, None | Some _, None, None | None, None, Some _ -> true
| _ -> false)
~f_exn:(fun _ _ -> Time_slots_are_not_disjoint)
time_slots
let check_if_normalized (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
time_slots
|> check_if_valid
|> check_if_not_empty
|> check_if_sorted
|> check_if_disjoint
end
module Filter = struct
let filter_invalid (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.filter Time_slot.Check.is_valid time_slots
let filter_invalid_list (time_slots : Time_slot.t list) : Time_slot.t list =
List.filter Time_slot.Check.is_valid time_slots
let filter_empty (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
Seq.filter Time_slot.Check.is_not_empty time_slots
let filter_empty_list (time_slots : Time_slot.t list) : Time_slot.t list =
List.filter Time_slot.Check.is_not_empty time_slots
end
module Sort = struct
let sort_time_slots_list ?(skip_check = false) (time_slots : Time_slot.t list)
: Time_slot.t list =
time_slots
|> (fun l ->
if skip_check then l
else l |> List.to_seq |> Check.check_if_valid |> List.of_seq)
|> List.sort Time_slot.compare
let sort_uniq_time_slots_list ?(skip_check = false)
(time_slots : Time_slot.t list) : Time_slot.t list =
time_slots
|> (fun l ->
if skip_check then l
else l |> List.to_seq |> Check.check_if_valid |> List.of_seq)
|> List.sort_uniq Time_slot.compare
let sort_uniq_time_slots ?(skip_check = false)
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> List.of_seq
|> List.sort_uniq Time_slot.compare
|> List.to_seq
let sort_time_slots ?(skip_check = false) (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> List.of_seq
|> List.sort Time_slot.compare
|> List.to_seq
end
module Join_internal = struct
let join (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux cur time_slots =
match time_slots () with
| Seq.Nil -> (
match cur with None -> Seq.empty | Some x -> Seq.return x )
| Seq.Cons ((start, end_exc), rest) -> (
match cur with
| None -> aux (Some (start, end_exc)) rest
| Some cur -> (
match Time_slot.join cur (start, end_exc) with
| Some x -> aux (Some x) rest
| None ->
fun () -> Seq.Cons (cur, aux (Some (start, end_exc)) rest) ) )
in
aux None time_slots
end
let join ?(skip_check = false) time_slots =
time_slots
|> (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> Join_internal.join
module Normalize = struct
let normalize ?(skip_filter_invalid = false) ?(skip_filter_empty = false)
?(skip_sort = false) time_slots =
time_slots
|> (fun s -> if skip_filter_invalid then s else Filter.filter_invalid s)
|> (fun s -> if skip_filter_empty then s else Filter.filter_empty s)
|> (fun s -> if skip_sort then s else Sort.sort_uniq_time_slots s)
|> Join_internal.join
let normalize_list_in_seq_out ?(skip_filter_invalid = false)
?(skip_filter_empty = false) ?(skip_sort = false) time_slots =
time_slots
|> List.to_seq
|> normalize ~skip_filter_invalid ~skip_filter_empty ~skip_sort
end
module Slice_internal = struct
let slice_start ~start (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux start time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), rest) ->
if start <= ts_start then
time_slots
else if ts_start < start && start < ts_end_exc then
fun () -> Seq.Cons ((start, ts_end_exc), rest)
else
aux start rest
in
aux start time_slots
let slice_end_exc ~end_exc (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
let rec aux end_exc time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), rest) ->
if end_exc <= ts_start then
aux end_exc Seq.empty
else if ts_start < end_exc && end_exc < ts_end_exc then
fun () -> Seq.Cons ((ts_start, end_exc), aux end_exc Seq.empty)
else
fun () -> Seq.Cons ((ts_start, ts_end_exc), aux end_exc rest)
in
aux end_exc time_slots
end
module Slice_rev_internal = struct
let slice_start ~start (time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux acc start time_slots =
match time_slots () with
| Seq.Nil -> List.rev acc |> List.to_seq
| Seq.Cons ((ts_start, ts_end_exc), slots) ->
if start <= ts_start then
entire time slot is after start , add to acc
aux ((ts_start, ts_end_exc) :: acc) start slots
else if ts_start < start && start < ts_end_exc then
aux ((start, ts_end_exc) :: acc) start slots
else
aux acc start Seq.empty
in
aux [] start time_slots
let slice_end_exc ~end_exc (time_slots : Time_slot.t Seq.t) :
Time_slot.t Seq.t =
let rec aux end_exc time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((ts_start, ts_end_exc), slots) ->
if ts_end_exc <= end_exc then
time_slots
else if ts_start < end_exc && end_exc < ts_end_exc then
OSeq.cons (ts_start, end_exc) slots
else
aux end_exc slots
in
aux end_exc time_slots
end
module Slice = struct
let slice ?(skip_check = false) ?start ?end_exc time_slots =
time_slots
|> (fun s ->
if skip_check then s
else
s
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted)
|> (fun s ->
match start with
| None -> s
| Some start -> Slice_internal.slice_start ~start s)
|> fun s ->
match end_exc with
| None -> s
| Some end_exc -> Slice_internal.slice_end_exc ~end_exc s
let slice_rev ?(skip_check = false) ?start ?end_exc time_slots =
time_slots
|> (fun s ->
if skip_check then s
else
s
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted_rev)
|> (fun s ->
match start with
| None -> s
| Some start -> Slice_rev_internal.slice_start ~start s)
|> fun s ->
match end_exc with
| None -> s
| Some end_exc -> Slice_rev_internal.slice_end_exc ~end_exc s
end
let relative_complement ?(skip_check = false) ~(not_mem_of : Time_slot.t Seq.t)
(mem_of : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux mem_of not_mem_of =
match (mem_of (), not_mem_of ()) with
| Seq.Nil, _ -> Seq.empty
| _, Seq.Nil -> mem_of
| ( Seq.Cons (mem_of_ts, mem_of_rest),
Seq.Cons (not_mem_of_ts, not_mem_of_rest) ) -> (
let mem_of () = Seq.Cons (mem_of_ts, mem_of_rest) in
let not_mem_of () = Seq.Cons (not_mem_of_ts, not_mem_of_rest) in
match Time_slot.overlap_of_a_over_b ~a:mem_of_ts ~b:not_mem_of_ts with
| None, None, None ->
mem_of_ts is empty , drop mem_of_ts
aux mem_of_rest not_mem_of
| Some _, None, None ->
mem_of_ts is before not_mem_of_ts entirely , output mem_of
fun () -> Seq.Cons (mem_of_ts, aux mem_of_rest not_mem_of)
| None, None, Some _ ->
aux mem_of not_mem_of_rest
| Some (start, end_exc), Some _, None ->
fun () -> Seq.Cons ((start, end_exc), aux mem_of_rest not_mem_of)
| None, Some _, None -> aux mem_of_rest not_mem_of
| None, Some _, Some (start, end_exc) ->
let mem_of () = Seq.Cons ((start, end_exc), mem_of_rest) in
aux mem_of not_mem_of_rest
| Some (start1, end_exc1), _, Some (start2, end_exc2) ->
let mem_of () = Seq.Cons ((start2, end_exc2), mem_of_rest) in
fun () -> Seq.Cons ((start1, end_exc1), aux mem_of not_mem_of_rest)
)
in
let mem_of =
if skip_check then mem_of
else
mem_of
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let not_mem_of =
if skip_check then not_mem_of
else
not_mem_of
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
aux mem_of not_mem_of
let invert ?(skip_check = false) ~start ~end_exc
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
relative_complement ~skip_check ~not_mem_of:time_slots
(Seq.return (start, end_exc))
let inter ?(skip_check = false) (time_slots1 : Time_slot.t Seq.t)
(time_slots2 : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots1 time_slots2 : Time_slot.t Seq.t =
match (time_slots1 (), time_slots2 ()) with
| Seq.Nil, _ -> Seq.empty
| _, Seq.Nil -> Seq.empty
| Seq.Cons ((start1, end_exc1), rest1), Seq.Cons ((start2, end_exc2), rest2)
->
if end_exc1 < start2 then
1 is before 2 entirely , drop 1 , keep 2
aux rest1 time_slots2
else if end_exc2 < start1 then
2 is before 1 entirely , keep 1 , drop 2
aux time_slots1 rest2
else
let overlap_start = max start1 start2 in
let overlap_end_exc = min end_exc1 end_exc2 in
let s1 = if end_exc1 <= overlap_end_exc then rest1 else time_slots1 in
let s2 = if end_exc2 <= overlap_end_exc then rest2 else time_slots2 in
if overlap_start < overlap_end_exc then
fun () -> Seq.Cons ((overlap_start, overlap_end_exc), aux s1 s2)
else aux s1 s2
in
let time_slots1 =
if skip_check then time_slots1
else
time_slots1
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else
time_slots2
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
aux time_slots1 time_slots2
module Merge = struct
let merge ?(skip_check = false) (time_slots1 : Time_slot.t Seq.t)
(time_slots2 : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots1 time_slots2 =
match (time_slots1 (), time_slots2 ()) with
| Seq.Nil, s | s, Seq.Nil -> fun () -> s
| Seq.Cons (x1, rest1), Seq.Cons (x2, rest2) ->
let ts1 () = Seq.Cons (x1, rest1) in
let ts2 () = Seq.Cons (x2, rest2) in
if Time_slot.le x1 x2 then fun () -> Seq.Cons (x1, aux rest1 ts2)
else fun () -> Seq.Cons (x2, aux rest2 ts1)
in
let time_slots1 =
if skip_check then time_slots1
else time_slots1 |> Check.check_if_valid |> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else time_slots2 |> Check.check_if_valid |> Check.check_if_sorted
in
aux time_slots1 time_slots2
let merge_multi_seq ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
Seq.fold_left
(fun acc time_slots -> merge ~skip_check acc time_slots)
Seq.empty time_slot_batches
let merge_multi_list ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
List.to_seq time_slot_batches |> merge_multi_seq ~skip_check
end
module Round_robin = struct
let collect_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t list) : Time_slot.t option list Seq.t =
batches
|> List.map (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> Seq_utils.collect_round_robin Time_slot.le
let merge_multi_list_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
collect_round_robin_non_decreasing ~skip_check batches
|> Seq.flat_map (fun l -> List.to_seq l |> Seq.filter_map (fun x -> x))
let merge_multi_seq_round_robin_non_decreasing ?(skip_check = false)
(batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
batches
|> List.of_seq
|> merge_multi_list_round_robin_non_decreasing ~skip_check
end
module Union = struct
let union ?(skip_check = false) time_slots1 time_slots2 =
let time_slots1 =
if skip_check then time_slots1
else
time_slots1
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
let time_slots2 =
if skip_check then time_slots2
else
time_slots2
|> Check.check_if_valid
|> Check.check_if_disjoint
|> Check.check_if_sorted
in
Merge.merge time_slots1 time_slots2
|> Normalize.normalize ~skip_filter_invalid:true ~skip_filter_empty:true
~skip_sort:true
let union_multi_seq ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t Seq.t) : Time_slot.t Seq.t =
Seq.fold_left
(fun acc time_slots -> union ~skip_check acc time_slots)
Seq.empty time_slot_batches
let union_multi_list ?(skip_check = false)
(time_slot_batches : Time_slot.t Seq.t list) : Time_slot.t Seq.t =
List.to_seq time_slot_batches |> union_multi_seq ~skip_check
end
let chunk ?(skip_check = false) ?(drop_partial = false) ~chunk_size
(time_slots : Time_slot.t Seq.t) : Time_slot.t Seq.t =
let rec aux time_slots =
match time_slots () with
| Seq.Nil -> Seq.empty
| Seq.Cons ((start, end_exc), rest) ->
let chunk_end_exc = min end_exc (start +^ chunk_size) in
let size = chunk_end_exc -^ start in
if size = 0L || (size < chunk_size && drop_partial) then aux rest
else
let rest () = Seq.Cons ((chunk_end_exc, end_exc), rest) in
fun () -> Seq.Cons ((start, chunk_end_exc), aux rest)
in
time_slots
|> (fun s -> if skip_check then s else s |> Check.check_if_valid)
|> aux
module Sum = struct
let sum_length ?(skip_check = false) (time_slots : Time_slot.t Seq.t) : int64
=
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> Seq.fold_left (fun acc (start, end_exc) -> acc +^ (end_exc -^ start)) 0L
let sum_length_list ?(skip_check = false) (time_slots : Time_slot.t list) :
int64 =
time_slots |> List.to_seq |> sum_length ~skip_check
end
module Bound = struct
let min_start_and_max_end_exc ?(skip_check = false)
(time_slots : Time_slot.t Seq.t) : (int64 * int64) option =
time_slots
|> (fun s -> if skip_check then s else Check.check_if_valid s)
|> Seq.fold_left
(fun acc (start, end_exc) ->
match acc with
| None -> Some (start, end_exc)
| Some (min_start, max_end_exc) ->
Some (min min_start start, max max_end_exc end_exc))
None
let min_start_and_max_end_exc_list ?(skip_check = false)
(time_slots : Time_slot.t list) : (int64 * int64) option =
time_slots |> List.to_seq |> min_start_and_max_end_exc ~skip_check
end
let shift_list ~offset (time_slots : Time_slot.t list) : Time_slot.t list =
List.map
(fun (start, end_exc) -> (start +^ offset, end_exc +^ offset))
time_slots
let equal (time_slots1 : Time_slot.t list) (time_slots2 : Time_slot.t list) :
bool =
let time_slots1 =
time_slots1 |> List.to_seq |> Normalize.normalize |> List.of_seq
in
let time_slots2 =
time_slots2 |> List.to_seq |> Normalize.normalize |> List.of_seq
in
time_slots1 = time_slots2
let a_is_subset_of_b ~(a : Time_slot.t Seq.t) ~(b : Time_slot.t Seq.t) : bool =
let inter = inter a b |> List.of_seq in
let a = List.of_seq a in
a = inter
let count_overlap ?(skip_check = false) (time_slots : Time_slot.t Seq.t) :
(Time_slot.t * int) Seq.t =
let flatten_buffer buffer =
buffer
|> List.sort (fun (x, _count) (y, _count) -> Time_slot.compare x y)
|> List.to_seq
|> Seq.flat_map (fun (x, count) ->
OSeq.(0 --^ count) |> Seq.map (fun _ -> x))
in
let flush_buffer_to_input buffer time_slots =
Merge.merge (flatten_buffer buffer) time_slots
in
let rec aux (cur : ((int64 * int64) * int) option)
(buffer : ((int64 * int64) * int) list) (time_slots : Time_slot.t Seq.t) :
(Time_slot.t * int) Seq.t =
match time_slots () with
| Seq.Nil -> (
match buffer with
| [] -> (
match cur with None -> Seq.empty | Some cur -> Seq.return cur )
| buffer -> aux cur [] (flatten_buffer buffer) )
| Seq.Cons (x, rest) -> (
let s () = Seq.Cons (x, rest) in
match cur with
| None -> (
match buffer with
| [] -> aux (Some (x, 1)) [] rest
| buffer -> aux None [] (flush_buffer_to_input buffer s) )
| Some ((cur_start, cur_end_exc), cur_count) -> (
match
Time_slot.overlap_of_a_over_b ~a:x ~b:(cur_start, cur_end_exc)
with
| None, None, None -> aux cur buffer rest
| Some _, _, _ ->
failwith "Unexpected case, time slots are not sorted"
| None, Some (start, end_exc), None
| None, Some (start, _), Some (_, end_exc) ->
if start = cur_start then
if end_exc < cur_end_exc then
failwith "Unexpected case, time slots are not sorted"
else if end_exc = cur_end_exc then
aux
(Some ((cur_start, cur_end_exc), succ cur_count))
buffer rest
else
aux
(Some ((cur_start, cur_end_exc), succ cur_count))
(((cur_end_exc, end_exc), 1) :: buffer)
rest
else fun () ->
Seq.Cons
( ((cur_start, start), cur_count),
let buffer =
if end_exc < cur_end_exc then
((start, end_exc), succ cur_count)
:: ((end_exc, cur_end_exc), cur_count)
:: buffer
else if end_exc = cur_end_exc then
((start, cur_end_exc), succ cur_count) :: buffer
else
((start, cur_end_exc), succ cur_count)
:: ((cur_end_exc, end_exc), 1)
:: buffer
in
aux None buffer rest )
| None, None, Some _ ->
fun () ->
Seq.Cons
(((cur_start, cur_end_exc), cur_count), aux None buffer s) )
)
in
time_slots
|> (fun s ->
if skip_check then s
else s |> Check.check_if_valid |> Check.check_if_sorted)
|> aux None []
module Serialize = struct
let pack_time_slots time_slots =
List.map Time_slot.Serialize.pack_time_slot time_slots
end
module Deserialize = struct
let unpack_time_slots time_slots =
List.map Time_slot.Deserialize.unpack_time_slot time_slots
end
|
ddbe0059be82949a275ee92a2d64c94485795c19f84b24b987a426c555790e4d | umd-cmsc330/cmsc330spring22 | disc5_sol.ml | (* Typing Practice *)
1) let f x y = x + y
int -> int -> int
2) let f x y = [x; y]
'a -> 'a -> 'a list
3)
let f a =
if a then 1 else "hi"
INVALID - Can't have two different return types
4)
let f a b =
if a then 0 else b
bool -> int -> int
5)
let f a b c =
let d = "hi" ^ a ^ b ^ c in
d == "hello"
String -> String -> String -> bool
(* Creating functions *)
1) float -> float -> float
Ex.
let f a b = a +. b
2) 'a -> 'b -> 'b list
Ex.
let f a b = [b]
3) int -> float -> int
Ex.
let f a b = if b = 0.1 then a else 1
4) 'a -> 'a -> 'a list
Ex.
let f a b = [a; b]
(* Records and New Types *)
1)
type hello = (str * int)
let a: hello = ("a",5)
2)
type Coin = Heads | Tails
let b: Coin = Heads
3)
type date = {month: string, day: int}
let today = {day=16; year=2017}
today.day | null | https://raw.githubusercontent.com/umd-cmsc330/cmsc330spring22/38f025e4eaf567c6802c6ade3936e4e0f994092a/discussions/d5_typing/disc5_sol.ml | ocaml | Typing Practice
Creating functions
Records and New Types |
1) let f x y = x + y
int -> int -> int
2) let f x y = [x; y]
'a -> 'a -> 'a list
3)
let f a =
if a then 1 else "hi"
INVALID - Can't have two different return types
4)
let f a b =
if a then 0 else b
bool -> int -> int
5)
let f a b c =
let d = "hi" ^ a ^ b ^ c in
d == "hello"
String -> String -> String -> bool
1) float -> float -> float
Ex.
let f a b = a +. b
2) 'a -> 'b -> 'b list
Ex.
let f a b = [b]
3) int -> float -> int
Ex.
let f a b = if b = 0.1 then a else 1
4) 'a -> 'a -> 'a list
Ex.
let f a b = [a; b]
1)
type hello = (str * int)
let a: hello = ("a",5)
2)
type Coin = Heads | Tails
let b: Coin = Heads
3)
type date = {month: string, day: int}
let today = {day=16; year=2017}
today.day |
fc38e68403338726835171d1c0af0f88ef9042ddc6804bda9d0327dc38f1ab2f | yzh44yzh/practical_erlang | short_link_test.erl | -module(short_link_test).
-include_lib("eunit/include/eunit.hrl").
%%% module API
create_short_test() ->
State1 = short_link:init(),
{Short1, State2} = short_link:create_short("", State1),
{Short2, State3} = short_link:create_short("", State2),
{Short3, State4} = short_link:create_short("", State3),
{Short4, State5} = short_link:create_short("", State4),
?assertMatch({Short1, _}, short_link:create_short("", State5)),
?assertMatch({Short2, _}, short_link:create_short("", State5)),
?assertMatch({Short3, _}, short_link:create_short("", State5)),
?assertMatch({Short4, _}, short_link:create_short("", State5)),
ok.
get_long_test() ->
State0 = short_link:init(),
?assertEqual({error, not_found}, short_link:get_long("foobar", State0)),
{Short1, State1} = short_link:create_short("", State0),
?assertEqual({ok, ""}, short_link:get_long(Short1, State1)),
{Short2, State2} = short_link:create_short("", State1),
?assertEqual({ok, ""}, short_link:get_long(Short2, State2)),
{Short3, State3} = short_link:create_short("", State2),
?assertEqual({ok, ""}, short_link:get_long(Short3, State3)),
{Short4, State4} = short_link:create_short("", State3),
?assertEqual({ok, ""}, short_link:get_long(Short4, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short1, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short2, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short3, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short4, State4)),
?assertEqual({error, not_found}, short_link:get_long("bla-bla-bla", State4)),
ok.
| null | https://raw.githubusercontent.com/yzh44yzh/practical_erlang/c9eec8cf44e152bf50d9bc6d5cb87fee4764f609/05_kv/solution/short_link_test.erl | erlang | module API | -module(short_link_test).
-include_lib("eunit/include/eunit.hrl").
create_short_test() ->
State1 = short_link:init(),
{Short1, State2} = short_link:create_short("", State1),
{Short2, State3} = short_link:create_short("", State2),
{Short3, State4} = short_link:create_short("", State3),
{Short4, State5} = short_link:create_short("", State4),
?assertMatch({Short1, _}, short_link:create_short("", State5)),
?assertMatch({Short2, _}, short_link:create_short("", State5)),
?assertMatch({Short3, _}, short_link:create_short("", State5)),
?assertMatch({Short4, _}, short_link:create_short("", State5)),
ok.
get_long_test() ->
State0 = short_link:init(),
?assertEqual({error, not_found}, short_link:get_long("foobar", State0)),
{Short1, State1} = short_link:create_short("", State0),
?assertEqual({ok, ""}, short_link:get_long(Short1, State1)),
{Short2, State2} = short_link:create_short("", State1),
?assertEqual({ok, ""}, short_link:get_long(Short2, State2)),
{Short3, State3} = short_link:create_short("", State2),
?assertEqual({ok, ""}, short_link:get_long(Short3, State3)),
{Short4, State4} = short_link:create_short("", State3),
?assertEqual({ok, ""}, short_link:get_long(Short4, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short1, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short2, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short3, State4)),
?assertEqual({ok, ""}, short_link:get_long(Short4, State4)),
?assertEqual({error, not_found}, short_link:get_long("bla-bla-bla", State4)),
ok.
|
5a5bb891a872ed69dada8cb43735f96d56882c3d0bc627d4b41258511f5b4a28 | erszcz/learning | ets_iter_sup.erl | -module(ets_iter_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
{ok, { {one_for_one, 5, 10}, [?CHILD(ets_iter_worker, worker)]} }.
| null | https://raw.githubusercontent.com/erszcz/learning/b21c58a09598e2aa5fa8a6909a80c81dc6be1601/erlang-ets-iter/src/ets_iter_sup.erl | erlang | API
Supervisor callbacks
Helper macro for declaring children of supervisor
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== | -module(ets_iter_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 5, 10}, [?CHILD(ets_iter_worker, worker)]} }.
|
8a979e27a0f282f3aad964fdd8de37fb1d5d7cd8d8b37bf53fb715b723d54862 | AccelerateHS/accelerate-llvm | Match.hs | # LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
Module : Data . Array . Accelerate . LLVM.Analysis . Match
Copyright : [ 2016 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.LLVM.Analysis.Match (
module Data.Array.Accelerate.Analysis.Match,
module Data.Array.Accelerate.LLVM.Analysis.Match,
) where
import Data.Array.Accelerate.Analysis.Match
import Data.Array.Accelerate.Array.Sugar
import Data.Typeable
-- Match reified shape types
--
matchShapeType
:: forall sh sh'. (Shape sh, Shape sh')
=> sh
-> sh'
-> Maybe (sh :~: sh')
matchShapeType _ _
| Just Refl <- matchTupleType (eltType (undefined::sh)) (eltType (undefined::sh'))
= gcast Refl
matchShapeType _ _
= Nothing
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-llvm/cf081587fecec23a19f68bfbd31334166868405e/accelerate-llvm/icebox/Data/Array/Accelerate/LLVM/Analysis/Match.hs | haskell | # LANGUAGE TypeOperators #
# OPTIONS_HADDOCK hide #
|
License : BSD3
Stability : experimental
Match reified shape types
| # LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
Module : Data . Array . Accelerate . LLVM.Analysis . Match
Copyright : [ 2016 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.LLVM.Analysis.Match (
module Data.Array.Accelerate.Analysis.Match,
module Data.Array.Accelerate.LLVM.Analysis.Match,
) where
import Data.Array.Accelerate.Analysis.Match
import Data.Array.Accelerate.Array.Sugar
import Data.Typeable
matchShapeType
:: forall sh sh'. (Shape sh, Shape sh')
=> sh
-> sh'
-> Maybe (sh :~: sh')
matchShapeType _ _
| Just Refl <- matchTupleType (eltType (undefined::sh)) (eltType (undefined::sh'))
= gcast Refl
matchShapeType _ _
= Nothing
|
9da6124d0190432ec52007094ba344ce7d9410bf9451a04a8f31aae356b37c13 | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Time.ES.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.Time.ES.Corpus
tests :: TestTree
tests = testGroup "ES Tests"
[ makeCorpusTest [Seal Time] corpus
, makeCorpusTest [Seal Time] latentCorpus
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Time/ES/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Time.ES.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.Time.ES.Corpus
tests :: TestTree
tests = testGroup "ES Tests"
[ makeCorpusTest [Seal Time] corpus
, makeCorpusTest [Seal Time] latentCorpus
]
|
1252a89347eb0b4df4f9d3599325aa25be9545abb9a8e948850c01d84cc68a33 | gfour/gic | ntak.hs | shuffle h x y z n =
if n `mod` 3 == 0 then
ntak shuffle h (n+3) (x-1) y z
else if n `mod` 3 == 1 then
ntak shuffle h (n+2) (y-1) z x
else
ntak shuffle h (n+1) (z-1) x y
ntak f h n x y z =
if x <= y then
h x y z
else
ntak f h n (f h x y z n)
(f h x y z (n+1))
(f h x y z (n+2))
third x y z = z
result = ntak shuffle third 0 32 16 8
result = ntak shuffle third 0 32 14 8
| null | https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/Examples/Num/ntak.hs | haskell | shuffle h x y z n =
if n `mod` 3 == 0 then
ntak shuffle h (n+3) (x-1) y z
else if n `mod` 3 == 1 then
ntak shuffle h (n+2) (y-1) z x
else
ntak shuffle h (n+1) (z-1) x y
ntak f h n x y z =
if x <= y then
h x y z
else
ntak f h n (f h x y z n)
(f h x y z (n+1))
(f h x y z (n+2))
third x y z = z
result = ntak shuffle third 0 32 16 8
result = ntak shuffle third 0 32 14 8
| |
239c0d101074f9e16ae52dc7ef0e06d06f26009efbb9cd2ebf8e814b1a9231e2 | ds-wizard/engine-backend | Detail_Documents_Preview_GET.hs | module Wizard.Api.Handler.Questionnaire.Detail_Documents_Preview_GET where
import Servant
import Shared.Api.Handler.Common
import Shared.Model.Context.TransactionState
import Shared.Model.Error.Error
import Wizard.Api.Handler.Common
import Wizard.Api.Resource.TemporaryFile.TemporaryFileDTO
import Wizard.Api.Resource.TemporaryFile.TemporaryFileJM ()
import Wizard.Localization.Messages.Public
import Wizard.Model.Context.BaseContext
import Wizard.Model.Document.Document
import Wizard.Service.Document.DocumentService
type Detail_Documents_Preview_GET =
Header "Authorization" String
:> Header "Host" String
:> "questionnaires"
:> Capture "qtnUuid" String
:> "documents"
:> "preview"
:> Get '[SafeJSON] (Headers '[Header "x-trace-uuid" String] TemporaryFileDTO)
detail_documents_preview_GET
:: Maybe String
-> Maybe String
-> String
-> BaseContextM (Headers '[Header "x-trace-uuid" String] TemporaryFileDTO)
detail_documents_preview_GET mTokenHeader mServerUrl qtnUuid =
getMaybeAuthServiceExecutor mTokenHeader mServerUrl $ \runInMaybeAuthService ->
runInMaybeAuthService Transactional $ do
(doc, fileDto) <- createDocumentPreviewForQtn qtnUuid
case doc.state of
DoneDocumentState -> addTraceUuidHeader fileDto
ErrorDocumentState ->
throwError $ SystemLogError (_ERROR_SERVICE_QTN__UNABLE_TO_GENERATE_DOCUMENT_PREVIEW $ doc.workerLog)
_ -> throwError AcceptedError
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/c6f40dc565c19d4b6672c5583d9cdc17c0549246/engine-wizard/src/Wizard/Api/Handler/Questionnaire/Detail_Documents_Preview_GET.hs | haskell | module Wizard.Api.Handler.Questionnaire.Detail_Documents_Preview_GET where
import Servant
import Shared.Api.Handler.Common
import Shared.Model.Context.TransactionState
import Shared.Model.Error.Error
import Wizard.Api.Handler.Common
import Wizard.Api.Resource.TemporaryFile.TemporaryFileDTO
import Wizard.Api.Resource.TemporaryFile.TemporaryFileJM ()
import Wizard.Localization.Messages.Public
import Wizard.Model.Context.BaseContext
import Wizard.Model.Document.Document
import Wizard.Service.Document.DocumentService
type Detail_Documents_Preview_GET =
Header "Authorization" String
:> Header "Host" String
:> "questionnaires"
:> Capture "qtnUuid" String
:> "documents"
:> "preview"
:> Get '[SafeJSON] (Headers '[Header "x-trace-uuid" String] TemporaryFileDTO)
detail_documents_preview_GET
:: Maybe String
-> Maybe String
-> String
-> BaseContextM (Headers '[Header "x-trace-uuid" String] TemporaryFileDTO)
detail_documents_preview_GET mTokenHeader mServerUrl qtnUuid =
getMaybeAuthServiceExecutor mTokenHeader mServerUrl $ \runInMaybeAuthService ->
runInMaybeAuthService Transactional $ do
(doc, fileDto) <- createDocumentPreviewForQtn qtnUuid
case doc.state of
DoneDocumentState -> addTraceUuidHeader fileDto
ErrorDocumentState ->
throwError $ SystemLogError (_ERROR_SERVICE_QTN__UNABLE_TO_GENERATE_DOCUMENT_PREVIEW $ doc.workerLog)
_ -> throwError AcceptedError
| |
fb51a7edaa03b0ea869fce190529e2207e883fbd3e71e026b67d841dbfced070 | ladderlife/cambo | utils.cljc | (ns cambo.utils)
#?(:clj
(defn- cljs-env? [env]
(boolean (:ns env))))
#?(:clj
(defmacro if-cljs
"Return `then` if we are generating cljs code and `else` for Clojure code."
[then else]
(if (cljs-env? &env) then else)))
| null | https://raw.githubusercontent.com/ladderlife/cambo/73b01aee04dc6a8b573783118c43c4d0508a4138/src/cambo/utils.cljc | clojure | (ns cambo.utils)
#?(:clj
(defn- cljs-env? [env]
(boolean (:ns env))))
#?(:clj
(defmacro if-cljs
"Return `then` if we are generating cljs code and `else` for Clojure code."
[then else]
(if (cljs-env? &env) then else)))
| |
0034ced3e3d51cc991facc0ce2e2037c574491e25c74893cd0404631dce67f00 | webyrd/n-grams-for-synthesis | srfi-3-reference.scm | ;;; Scheme Underground list-set library -*- Scheme -*-
;;;
Copyright ( c ) 1998 by . You may do as you please with
;;; this code as long as you do not remove this copyright notice or
;;; hold me liable for its use. Please send bug reports to .
;;; -Olin
;;; SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT
This is * draft * code for a SRFI proposal . If you see this notice in
;;; production code, you've got obsolete, bad source -- go find the final
;;; non-draft code on the Net.
;;; SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT
;;; Exported:
;;; lset= = list1 list2 ... -> boolean
;;; lset<= = list1 list2 ... -> boolean
;;;
;;; lset-adjoin = list elt1 ...
lset - union = list1 ...
;;; lset-intersection = list1 list2 ...
;;; lset-difference = list1 list2 ...
lset - xor = list1 ...
lset - diff+intersection = list1 list2 ...
;;; ... and their side effecting counterparts:
;;; lset-union! lset-intersection! lset-difference! lset-xor!
;;; lset-diff+intersection!
;;;
;;; adjoin {,q,v}: list elt1 ...
;;; union {,q,v} {,!}: list1 ...
intersection { , q , v } { , ! } : ...
list - difference { , q , v } { , ! } : ...
;;; list-xor {,q,v} {,!}: list1 ...
diff+intersection { , q , v } { , ! } : ...
;;; This is carefully tuned code; do not modify casually.
;;; - It is careful to share storage when possible;
;;; - Side-effecting code tries not to perform redundant writes.
;;; - It tries to avoid linear-time scans in special cases where constant-time
;;; computations can be performed.
;;; - It relies on similar properties from the list-lib code it calls.
;;; If there's a way to mark these procedures as candidates for integration,
;;; they should be so marked. It would also be nice if the n-ary ops could
;;; be unfolded by the compiler into a chain of binary-op applications. But
;;; this kind of compiler technology no longer exists in the Scheme world.
;;; This implementation is intended as a portable reference implementation
of my list - set package . With three exceptions , it is completely R4RS :
;;; - The (RECEIVE (var ...) mv-exp body ...) multi-value-return binding macro
;;; - The procedures defined in my list-lib package, for which there is also
;;; a portable reference implementation.
;;; Many calls to a parameter-checking procedure check-arg:
( define ( check - arg pred caller )
( let lp ( ( ) )
( if ( pred ) ( lp ( error " Bad argument " val pred caller ) ) ) ) )
;;; Note that this code is, of course, dependent upon standard bindings for
the R5RS procedures -- i.e. , it assumes that the variable CAR is bound
;;; to the procedure that takes the car of a list. If your Scheme
;;; implementation allows user code to alter the bindings of these procedures
;;; in a manner that would be visible to these definitions, then there might
;;; be trouble. You could consider horrible kludgery along the lines of
;;; (define fact
;;; (let ((= =) (- -) (* *))
;;; (letrec ((real-fact (lambda (n)
( if (= n 0 ) 1 ( * n ( real - fact ( - n 1 ) ) ) ) ) ) )
;;; real-fact)))
;;; Or you could consider shifting to a reasonable Scheme system that, say,
;;; has a module system protecting code from this kind of lossage.
;;;
;;; This code does a fair amount of run-time argument checking. If your
;;; Scheme system has a sophisticated compiler that can eliminate redundant
;;; error checks, this is no problem. However, if not, these checks incur
;;; some performance overhead -- and, in a safe Scheme implementation, they
;;; are in some sense redundant: if we don't check to see that the PROC
parameter is a procedure , we 'll find out anyway three lines later when
;;; we try to call the value. It's pretty easy to rip all this argument
;;; checking code out if it's inappropriate for your implementation -- just
;;; nuke every call to CHECK-ARG.
;;;
;;; On the other hand, if you *do* have a sophisticated compiler that will
actually perform soft - typing and eliminate redundant checks ( being
;;; the only possible candidate of which I'm aware), leaving these checks
;;; in can *help*, since their presence can be elided in redundant cases,
;;; and in cases where they are needed, performing the checks early, at
;;; procedure entry, can "lift" a check out of a loop.
;;;
;;; Finally, I have only checked the properties that can portably be checked
;;; with R5RS Scheme -- and this is not complete. You may wish to alter
;;; the CHECK-ARG parameter checks to perform extra, implementation-specific
;;; checks, such as procedure arity for higher-order values.
;;;
First the procedures that take a comparison function as an argument .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (%lset2<= = lis1 lis2) (every (lambda (x) (mem = x lis2)) lis1))
(define (lset<= = lis1 . lists)
(check-arg = procedure? lset<=)
(let lp ((s1 lis1) (rest lists))
(or (not (pair? rest))
(let ((s2 (car rest)) (rest (cdr rest)))
(and (or (eq? s2 s1) ; Fast path
(%lset2<= = s1 s2)) ; Real test
(lp s2 rest))))))
(define (lset= = lis1 . lists)
(check-arg = procedure? lset=)
(let lp ((s1 lis1) (rest lists))
(or (not (pair? rest))
(let ((s2 (car rest))
(rest (cdr rest)))
(and (or (eq? s1 s2) ; Fast path
(and (%lset2<= = s1 s2) (%lset2<= = s2 s1))) ; Real test
(lp s2 rest))))))
(define (lset-adjoin = lis . elts)
(check-arg = procedure? lset-adjoin)
(foldl (lambda (elt ans) (if (mem = elt ans) ans (cons elt ans)))
lis elts))
(define (lset-union = . lists)
(check-arg = procedure? lset-union)
(if (pair? lists)
(foldl (lambda (lis ans) ; Compute LIS + ANS.
(if (pair? ans)
(foldl (lambda (elt ans) (if (mem = elt ans) ans
(cons elt ans)))
ans lis)
Do n't copy LIS if you do n't have to .
(car lists)
(cdr lists))
'()))
(define (lset-union! = . lists)
(check-arg = procedure? lset-union!)
(if (pair? lists)
Splice new elts of LIS onto the front of ANS .
(if (pair? ans)
(pair-foldl (lambda (pair ans)
(if (mem = (car pair) ans) ans
(begin (set-cdr! pair ans) pair)))
ans lis)
Do n't scan if you do n't have to .
(car lists)
(cdr lists))
'()))
(define (lset-intersection = lis1 . lists)
(check-arg = procedure? lset-intersection)
(if (every pair? lists)
(foldl (lambda (lis residue) (filter (lambda (x) (mem = x lis)) residue))
lis1
lists)
Do n't do unnecessary scans of LIS1 / RESIDUE .
(define (lset-intersection! = lis1 . lists)
(check-arg = procedure? lset-intersection!)
(if (every pair? lists)
(foldl (lambda (lis residue) (filter! (lambda (x) (mem = x lis)) residue))
lis1
lists)
Do n't do unnecessary scans of LIS1 / RESIDUE .
(define (lset-difference = lis1 . lists)
(check-arg = procedure? lset-difference)
(foldl (lambda (lis residue)
(if (pair? lis)
(filter (lambda (x) (not (mem = x lis))) residue)
Do n't do unnecessary scans of RESIDUE .
lis1
lists))
(define (lset-difference! = lis1 . lists)
(check-arg = procedure? lset-difference!)
(foldl (lambda (lis residue)
(if (pair? lis)
(filter! (lambda (x) (not (mem = x lis))) residue)
Do n't do unnecessary scans of RESIDUE .
lis1
lists))
(define (lset-xor = . lists)
(check-arg = procedure? lset-xor)
(if (pair? lists) ; We don't really have to do this test, but WTF.
(foldl (lambda (a b) ; Compute A xor B:
(if (pair? a)
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection = a b)
(foldl (lambda (xb ans)
(if (mem = xb a-int-b) ans (cons xb ans)))
a-b
b))
b)) ; Don't copy B if we don't have to.
(car lists)
(cdr lists))
'()))
(define (lset-xor! = . lists)
(check-arg = procedure? lset-xor!)
(if (pair? lists) ; We don't really have to do this test, but WTF.
(foldl (lambda (a b) ; Compute A xor B:
(if (pair? a)
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection! = a b)
(pair-foldl (lambda (b-pair ans)
(if (mem = (car b-pair) a-int-b) ans
(begin (set-cdr! b-pair ans) b-pair)))
a-b
b))
b)) ; Don't copy B if we don't have to.
(car lists)
(cdr lists))
'()))
(define (lset-diff+intersection = lis1 . lists)
(check-arg = procedure? lset-diff+intersection)
(if (any pair? lists)
(partition (lambda (elt) (not (any (lambda (lis) (mem = elt lis))
lists)))
lis1)
(values lis1 '()))) ; Don't scan LIS1 if we don't have to.
(define (lset-diff+intersection! = lis1 . lists)
(check-arg = procedure? lset-diff+intersection!)
(if (any pair? lists)
(partition! (lambda (elt) (not (any (lambda (lis) (mem = elt lis))
lists)))
lis1)
(values lis1 '()))) ; Don't scan LIS1 if we don't have to.
;;; These are the variants with the built-in comparison functions
( EQUAL ? , EQ ? , EQV ? ) .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (adjoin list . elts) (apply lset-adjoin equal? list elts))
(define (adjoinq list . elts) (apply lset-adjoin eq? list elts))
(define (adjoinv list . elts) (apply lset-adjoin eqv? list elts))
(define (union . lists) (apply lset-union equal? lists))
(define (unionq . lists) (apply lset-union eq? lists))
(define (unionv . lists) (apply lset-union eqv? lists))
(define (union! . lists) (apply lset-union! equal? lists))
(define (unionq! . lists) (apply lset-union! eq? lists))
(define (unionv! . lists) (apply lset-union! eqv? lists))
(define (intersection lis1 . lists) (apply lset-intersection equal? lis1 lists))
(define (intersectionq lis1 . lists) (apply lset-intersection eq? lis1 lists))
(define (intersectionv lis1 . lists) (apply lset-intersection eqv? lis1 lists))
(define (intersection! lis1 . lists) (apply lset-intersection! equal? lis1 lists))
(define (intersectionq! lis1 . lists) (apply lset-intersection! eq? lis1 lists))
(define (intersectionv! lis1 . lists) (apply lset-intersection! eqv? lis1 lists))
(define (list-difference lis1 . lists) (apply lset-difference equal? lis1 lists))
(define (list-differenceq lis1 . lists) (apply lset-difference eq? lis1 lists))
(define (list-differencev lis1 . lists) (apply lset-difference eqv? lis1 lists))
(define (list-difference! lis1 . lists) (apply lset-difference! equal? lis1 lists))
(define (list-differenceq! lis1 . lists) (apply lset-difference! eq? lis1 lists))
(define (list-differencev! lis1 . lists) (apply lset-difference! eqv? lis1 lists))
(define (list-xor . lists) (apply lset-xor equal? lists))
(define (list-xorq . lists) (apply lset-xor eq? lists))
(define (list-xorv . lists) (apply lset-xor eqv? lists))
(define (list-xor! . lists) (apply lset-xor! equal? lists))
(define (list-xorq! . lists) (apply lset-xor! eq? lists))
(define (list-xorv! . lists) (apply lset-xor! eqv? lists))
(define (diff+intersection lis1 . lists)
(apply lset-diff+intersection equal? lis1 lists))
(define (diff+intersectionq lis1 . lists)
(apply lset-diff+intersection eq? lis1 lists))
(define (diff+intersectionv lis1 . lists)
(apply lset-diff+intersection eqv? lis1 lists))
(define (diff+intersection! lis1 . lists)
(apply lset-diff+intersection! equal? lis1 lists))
(define (diff+intersectionq! lis1 . lists)
(apply lset-diff+intersection! eq? lis1 lists))
(define (diff+intersectionv! lis1 . lists)
(apply lset-diff+intersection! eqv? lis1 lists))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-3/srfi-3-reference.scm | scheme | Scheme Underground list-set library -*- Scheme -*-
this code as long as you do not remove this copyright notice or
hold me liable for its use. Please send bug reports to .
-Olin
SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT
production code, you've got obsolete, bad source -- go find the final
non-draft code on the Net.
SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT -- SRFI DRAFT
Exported:
lset= = list1 list2 ... -> boolean
lset<= = list1 list2 ... -> boolean
lset-adjoin = list elt1 ...
lset-intersection = list1 list2 ...
lset-difference = list1 list2 ...
... and their side effecting counterparts:
lset-union! lset-intersection! lset-difference! lset-xor!
lset-diff+intersection!
adjoin {,q,v}: list elt1 ...
union {,q,v} {,!}: list1 ...
list-xor {,q,v} {,!}: list1 ...
This is carefully tuned code; do not modify casually.
- It is careful to share storage when possible;
- Side-effecting code tries not to perform redundant writes.
- It tries to avoid linear-time scans in special cases where constant-time
computations can be performed.
- It relies on similar properties from the list-lib code it calls.
If there's a way to mark these procedures as candidates for integration,
they should be so marked. It would also be nice if the n-ary ops could
be unfolded by the compiler into a chain of binary-op applications. But
this kind of compiler technology no longer exists in the Scheme world.
This implementation is intended as a portable reference implementation
- The (RECEIVE (var ...) mv-exp body ...) multi-value-return binding macro
- The procedures defined in my list-lib package, for which there is also
a portable reference implementation.
Many calls to a parameter-checking procedure check-arg:
Note that this code is, of course, dependent upon standard bindings for
to the procedure that takes the car of a list. If your Scheme
implementation allows user code to alter the bindings of these procedures
in a manner that would be visible to these definitions, then there might
be trouble. You could consider horrible kludgery along the lines of
(define fact
(let ((= =) (- -) (* *))
(letrec ((real-fact (lambda (n)
real-fact)))
Or you could consider shifting to a reasonable Scheme system that, say,
has a module system protecting code from this kind of lossage.
This code does a fair amount of run-time argument checking. If your
Scheme system has a sophisticated compiler that can eliminate redundant
error checks, this is no problem. However, if not, these checks incur
some performance overhead -- and, in a safe Scheme implementation, they
are in some sense redundant: if we don't check to see that the PROC
we try to call the value. It's pretty easy to rip all this argument
checking code out if it's inappropriate for your implementation -- just
nuke every call to CHECK-ARG.
On the other hand, if you *do* have a sophisticated compiler that will
the only possible candidate of which I'm aware), leaving these checks
in can *help*, since their presence can be elided in redundant cases,
and in cases where they are needed, performing the checks early, at
procedure entry, can "lift" a check out of a loop.
Finally, I have only checked the properties that can portably be checked
with R5RS Scheme -- and this is not complete. You may wish to alter
the CHECK-ARG parameter checks to perform extra, implementation-specific
checks, such as procedure arity for higher-order values.
Fast path
Real test
Fast path
Real test
Compute LIS + ANS.
We don't really have to do this test, but WTF.
Compute A xor B:
Compute a-b and a^b, then compute b-(a^b) and
cons it onto the front of a-b.
Don't copy B if we don't have to.
We don't really have to do this test, but WTF.
Compute A xor B:
Compute a-b and a^b, then compute b-(a^b) and
cons it onto the front of a-b.
Don't copy B if we don't have to.
Don't scan LIS1 if we don't have to.
Don't scan LIS1 if we don't have to.
These are the variants with the built-in comparison functions
| Copyright ( c ) 1998 by . You may do as you please with
This is * draft * code for a SRFI proposal . If you see this notice in
lset - union = list1 ...
lset - xor = list1 ...
lset - diff+intersection = list1 list2 ...
intersection { , q , v } { , ! } : ...
list - difference { , q , v } { , ! } : ...
diff+intersection { , q , v } { , ! } : ...
of my list - set package . With three exceptions , it is completely R4RS :
( define ( check - arg pred caller )
( let lp ( ( ) )
( if ( pred ) ( lp ( error " Bad argument " val pred caller ) ) ) ) )
the R5RS procedures -- i.e. , it assumes that the variable CAR is bound
( if (= n 0 ) 1 ( * n ( real - fact ( - n 1 ) ) ) ) ) ) )
parameter is a procedure , we 'll find out anyway three lines later when
actually perform soft - typing and eliminate redundant checks ( being
First the procedures that take a comparison function as an argument .
(define (%lset2<= = lis1 lis2) (every (lambda (x) (mem = x lis2)) lis1))
(define (lset<= = lis1 . lists)
(check-arg = procedure? lset<=)
(let lp ((s1 lis1) (rest lists))
(or (not (pair? rest))
(let ((s2 (car rest)) (rest (cdr rest)))
(lp s2 rest))))))
(define (lset= = lis1 . lists)
(check-arg = procedure? lset=)
(let lp ((s1 lis1) (rest lists))
(or (not (pair? rest))
(let ((s2 (car rest))
(rest (cdr rest)))
(lp s2 rest))))))
(define (lset-adjoin = lis . elts)
(check-arg = procedure? lset-adjoin)
(foldl (lambda (elt ans) (if (mem = elt ans) ans (cons elt ans)))
lis elts))
(define (lset-union = . lists)
(check-arg = procedure? lset-union)
(if (pair? lists)
(if (pair? ans)
(foldl (lambda (elt ans) (if (mem = elt ans) ans
(cons elt ans)))
ans lis)
Do n't copy LIS if you do n't have to .
(car lists)
(cdr lists))
'()))
(define (lset-union! = . lists)
(check-arg = procedure? lset-union!)
(if (pair? lists)
Splice new elts of LIS onto the front of ANS .
(if (pair? ans)
(pair-foldl (lambda (pair ans)
(if (mem = (car pair) ans) ans
(begin (set-cdr! pair ans) pair)))
ans lis)
Do n't scan if you do n't have to .
(car lists)
(cdr lists))
'()))
(define (lset-intersection = lis1 . lists)
(check-arg = procedure? lset-intersection)
(if (every pair? lists)
(foldl (lambda (lis residue) (filter (lambda (x) (mem = x lis)) residue))
lis1
lists)
Do n't do unnecessary scans of LIS1 / RESIDUE .
(define (lset-intersection! = lis1 . lists)
(check-arg = procedure? lset-intersection!)
(if (every pair? lists)
(foldl (lambda (lis residue) (filter! (lambda (x) (mem = x lis)) residue))
lis1
lists)
Do n't do unnecessary scans of LIS1 / RESIDUE .
(define (lset-difference = lis1 . lists)
(check-arg = procedure? lset-difference)
(foldl (lambda (lis residue)
(if (pair? lis)
(filter (lambda (x) (not (mem = x lis))) residue)
Do n't do unnecessary scans of RESIDUE .
lis1
lists))
(define (lset-difference! = lis1 . lists)
(check-arg = procedure? lset-difference!)
(foldl (lambda (lis residue)
(if (pair? lis)
(filter! (lambda (x) (not (mem = x lis))) residue)
Do n't do unnecessary scans of RESIDUE .
lis1
lists))
(define (lset-xor = . lists)
(check-arg = procedure? lset-xor)
(if (pair? a)
(receive (a-b a-int-b) (lset-diff+intersection = a b)
(foldl (lambda (xb ans)
(if (mem = xb a-int-b) ans (cons xb ans)))
a-b
b))
(car lists)
(cdr lists))
'()))
(define (lset-xor! = . lists)
(check-arg = procedure? lset-xor!)
(if (pair? a)
(receive (a-b a-int-b) (lset-diff+intersection! = a b)
(pair-foldl (lambda (b-pair ans)
(if (mem = (car b-pair) a-int-b) ans
(begin (set-cdr! b-pair ans) b-pair)))
a-b
b))
(car lists)
(cdr lists))
'()))
(define (lset-diff+intersection = lis1 . lists)
(check-arg = procedure? lset-diff+intersection)
(if (any pair? lists)
(partition (lambda (elt) (not (any (lambda (lis) (mem = elt lis))
lists)))
lis1)
(define (lset-diff+intersection! = lis1 . lists)
(check-arg = procedure? lset-diff+intersection!)
(if (any pair? lists)
(partition! (lambda (elt) (not (any (lambda (lis) (mem = elt lis))
lists)))
lis1)
( EQUAL ? , EQ ? , EQV ? ) .
(define (adjoin list . elts) (apply lset-adjoin equal? list elts))
(define (adjoinq list . elts) (apply lset-adjoin eq? list elts))
(define (adjoinv list . elts) (apply lset-adjoin eqv? list elts))
(define (union . lists) (apply lset-union equal? lists))
(define (unionq . lists) (apply lset-union eq? lists))
(define (unionv . lists) (apply lset-union eqv? lists))
(define (union! . lists) (apply lset-union! equal? lists))
(define (unionq! . lists) (apply lset-union! eq? lists))
(define (unionv! . lists) (apply lset-union! eqv? lists))
(define (intersection lis1 . lists) (apply lset-intersection equal? lis1 lists))
(define (intersectionq lis1 . lists) (apply lset-intersection eq? lis1 lists))
(define (intersectionv lis1 . lists) (apply lset-intersection eqv? lis1 lists))
(define (intersection! lis1 . lists) (apply lset-intersection! equal? lis1 lists))
(define (intersectionq! lis1 . lists) (apply lset-intersection! eq? lis1 lists))
(define (intersectionv! lis1 . lists) (apply lset-intersection! eqv? lis1 lists))
(define (list-difference lis1 . lists) (apply lset-difference equal? lis1 lists))
(define (list-differenceq lis1 . lists) (apply lset-difference eq? lis1 lists))
(define (list-differencev lis1 . lists) (apply lset-difference eqv? lis1 lists))
(define (list-difference! lis1 . lists) (apply lset-difference! equal? lis1 lists))
(define (list-differenceq! lis1 . lists) (apply lset-difference! eq? lis1 lists))
(define (list-differencev! lis1 . lists) (apply lset-difference! eqv? lis1 lists))
(define (list-xor . lists) (apply lset-xor equal? lists))
(define (list-xorq . lists) (apply lset-xor eq? lists))
(define (list-xorv . lists) (apply lset-xor eqv? lists))
(define (list-xor! . lists) (apply lset-xor! equal? lists))
(define (list-xorq! . lists) (apply lset-xor! eq? lists))
(define (list-xorv! . lists) (apply lset-xor! eqv? lists))
(define (diff+intersection lis1 . lists)
(apply lset-diff+intersection equal? lis1 lists))
(define (diff+intersectionq lis1 . lists)
(apply lset-diff+intersection eq? lis1 lists))
(define (diff+intersectionv lis1 . lists)
(apply lset-diff+intersection eqv? lis1 lists))
(define (diff+intersection! lis1 . lists)
(apply lset-diff+intersection! equal? lis1 lists))
(define (diff+intersectionq! lis1 . lists)
(apply lset-diff+intersection! eq? lis1 lists))
(define (diff+intersectionv! lis1 . lists)
(apply lset-diff+intersection! eqv? lis1 lists))
|
bf40ef32ecc1ac2b3fa7bb28c02cd520346afa883cf3cff4c15df6ae2a4acaa1 | plumatic/dommy | utils.clj | (ns dommy.utils
(:require
[clojure.string :as str]))
(defn as-str
"Coerces strings and keywords to strings, while preserving namespace of
namespaced keywords"
[s]
(if (keyword? s)
(str (some-> (namespace s) (str "/")) (name s))
s))
(defn constant? [data]
(some #(% data) [number? keyword? string?]))
(defn all-constant? [data]
(cond
(coll? data) (every? all-constant? data)
(constant? data) true))
(defn single-selector? [data]
(re-matches #"^\S+$" (as-str data)))
(defn id-selector? [s]
(re-matches #"^#[\w-]+$" (as-str s)))
(defn class-selector? [s]
(re-matches #"^\.[a-z_-][a-z0-9_-]*$" (as-str s)))
(defn tag-selector? [s]
(re-matches #"^[a-z_-][a-z0-9_-]*$" (as-str s)))
(defn selector [data]
(cond
(coll? data) (str/join " " (map selector data))
(constant? data) (as-str data)))
(defn selector-form [data]
(if (all-constant? data)
(selector data)
`(dommy.core/selector ~data)))
(defn query-selector [base data]
`(.querySelector ~base ~(selector-form data)))
(defn query-selector-all [base data]
`(dommy.utils/->Array
(.querySelectorAll ~base ~(selector-form data))))
| null | https://raw.githubusercontent.com/plumatic/dommy/ba5a6f31bc185c32c851e052091f315114ead088/src/dommy/utils.clj | clojure | (ns dommy.utils
(:require
[clojure.string :as str]))
(defn as-str
"Coerces strings and keywords to strings, while preserving namespace of
namespaced keywords"
[s]
(if (keyword? s)
(str (some-> (namespace s) (str "/")) (name s))
s))
(defn constant? [data]
(some #(% data) [number? keyword? string?]))
(defn all-constant? [data]
(cond
(coll? data) (every? all-constant? data)
(constant? data) true))
(defn single-selector? [data]
(re-matches #"^\S+$" (as-str data)))
(defn id-selector? [s]
(re-matches #"^#[\w-]+$" (as-str s)))
(defn class-selector? [s]
(re-matches #"^\.[a-z_-][a-z0-9_-]*$" (as-str s)))
(defn tag-selector? [s]
(re-matches #"^[a-z_-][a-z0-9_-]*$" (as-str s)))
(defn selector [data]
(cond
(coll? data) (str/join " " (map selector data))
(constant? data) (as-str data)))
(defn selector-form [data]
(if (all-constant? data)
(selector data)
`(dommy.core/selector ~data)))
(defn query-selector [base data]
`(.querySelector ~base ~(selector-form data)))
(defn query-selector-all [base data]
`(dommy.utils/->Array
(.querySelectorAll ~base ~(selector-form data))))
| |
0162b111d5b08a8ebcc40623b299895d98c7db370e51bc9931093a7759e88a91 | iamFIREcracker/adventofcode | day11.lisp | (defpackage :aoc/2018/11 #.cl-user::*aoc-use*)
(in-package :aoc/2018/11)
(defun power-level (x y serial-number)
(let ((rack-id (+ x 10)))
(->< rack-id
(* >< y)
(+ >< serial-number)
(* >< rack-id)
(mod (floor >< 100) 10)
(- >< 5))))
(defun power-grid (size serial-number)
(let* ((grid (make-array `(,size ,size))))
(dotimes (y size)
(dotimes (x size)
(setf (aref grid y x) (power-level (1+ x) (1+ y) serial-number))))
grid))
(defun max-square-of-energy (st square-size &aux best-pos best-value)
(loop
:with grid-size = (array-dimension st 0)
:for top :from 0 :below (- grid-size (1- square-size))
:do (loop
:for left :from 0 :below (- grid-size (1- square-size))
:for bottom = (+ top (1- square-size))
:for right = (+ left (1- square-size))
:for power = (st-area-of st top left bottom right)
:do (when (or (not best-value) (> power best-value))
(setf best-pos (list left top)
best-value power))))
(values best-pos best-value))
(define-solution (2018 11) (data read-integer)
(let* ((grid (power-grid 300 data))
(st (make-summedarea-table grid)))
(values
(destructuring-bind (x y) (max-square-of-energy st 3)
(mkstrc (1+ x) (1+ y)))
(loop
:with best-pos
:with best-value
:with best-size
:for size :from 1 :to 300
:do (multiple-value-bind (pos value) (max-square-of-energy st size)
(when (or (not best-value) (> value best-value))
(setf best-pos pos
best-value value
best-size size)))
:finally (return (destructuring-bind (x y) best-pos
(mkstrc (1+ x) (1+ y) best-size)))))))
(define-test (2018 11) ("21,41" "227,199,19"))
| null | https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2018/day11.lisp | lisp | (defpackage :aoc/2018/11 #.cl-user::*aoc-use*)
(in-package :aoc/2018/11)
(defun power-level (x y serial-number)
(let ((rack-id (+ x 10)))
(->< rack-id
(* >< y)
(+ >< serial-number)
(* >< rack-id)
(mod (floor >< 100) 10)
(- >< 5))))
(defun power-grid (size serial-number)
(let* ((grid (make-array `(,size ,size))))
(dotimes (y size)
(dotimes (x size)
(setf (aref grid y x) (power-level (1+ x) (1+ y) serial-number))))
grid))
(defun max-square-of-energy (st square-size &aux best-pos best-value)
(loop
:with grid-size = (array-dimension st 0)
:for top :from 0 :below (- grid-size (1- square-size))
:do (loop
:for left :from 0 :below (- grid-size (1- square-size))
:for bottom = (+ top (1- square-size))
:for right = (+ left (1- square-size))
:for power = (st-area-of st top left bottom right)
:do (when (or (not best-value) (> power best-value))
(setf best-pos (list left top)
best-value power))))
(values best-pos best-value))
(define-solution (2018 11) (data read-integer)
(let* ((grid (power-grid 300 data))
(st (make-summedarea-table grid)))
(values
(destructuring-bind (x y) (max-square-of-energy st 3)
(mkstrc (1+ x) (1+ y)))
(loop
:with best-pos
:with best-value
:with best-size
:for size :from 1 :to 300
:do (multiple-value-bind (pos value) (max-square-of-energy st size)
(when (or (not best-value) (> value best-value))
(setf best-pos pos
best-value value
best-size size)))
:finally (return (destructuring-bind (x y) best-pos
(mkstrc (1+ x) (1+ y) best-size)))))))
(define-test (2018 11) ("21,41" "227,199,19"))
| |
fd5a3785a5a8124db545c0e851481f18cd27bd4887e38dacbf7871ba40e3734a | TensorWrench/lager_extras | lager_json_formatter.erl | % Copyright 2012 Tensor Wrench LLC. All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above
% copyright notice, this list of conditions and the following disclaimer
% in the documentation and/or other materials provided with the
% distribution.
* Neither the name of TensorWrench , LLC nor the names of its
% contributors may be used to endorse or promote products derived from
% this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-module(lager_json_formatter).
%%
%% Include files
%%
-include_lib("lager/include/lager.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%%
%% Exported Functions
%%
-export([format/2]).
%%
%% API Functions
%%
-spec format(#lager_log_message{},list()) -> iolist().
format(#lager_log_message{}=Message,Config) ->
Encoder=lager_extras_mochijson2:encoder([{handler,fun json_handler/1},{utf8,proplists:get_value(utf8,Config,true)}]),
Encoder(Message).
%% -record(lager_log_message,{
%% destinations,
%% metadata,
%% severity_as_int,
%% timestamp,
%% message
%% }).
json_handler(#lager_log_message{message=Message,metadata=Metadata,timestamp={Date,Time},severity_as_int=Level}) ->
Severity=lager_util:num_to_level(Level),
{struct,[{date,list_to_binary(Date)},
{time,list_to_binary(Time)},
{severity,Severity},
{message,iolist_to_binary(Message)}
| [ {K,make_printable(V)} || {K,V} <- Metadata]]}.
make_printable(A) when is_atom(A) orelse is_binary(A) orelse is_number(A) -> A;
make_printable(P) when is_pid(P) -> iolist_to_binary(pid_to_list(P));
make_printable(Other) -> iolist_to_binary(io_lib:format("~p",[Other])).
-ifdef(TEST).
basic_test_() ->
[{"Just a plain message.",
?_assertEqual(iolist_to_binary(<<"{\"date\":\"Day\",\"time\":\"Time\",\"severity\":\"error\",\"message\":\"Message\"}">>),
iolist_to_binary(format(#lager_log_message{timestamp={"Day","Time"},
message="Message",
severity_as_int=lager_util:level_to_num(error),
metadata=[]},
[])))
},
{"Just a plain with standard metadata.",
?_assertEqual(iolist_to_binary([<<"{\"date\":\"Day\",\"time\":\"Time\",\"severity\":\"error\",\"message\":\"Message\"">>,
<<",\"module\":\"">>,atom_to_list(?MODULE),$",
<<",\"function\":\"my_function\"">>,
<<",\"line\":999">>,
<<",\"pid\":\"\\\"">>, pid_to_list(self()),<<"\\\"\"">>,
"}"
]),
iolist_to_binary(format(#lager_log_message{timestamp={"Day","Time"},
message="Message",
severity_as_int=lager_util:level_to_num(error),
metadata=[{module,?MODULE},{function,my_function},{line,999},{pid,pid_to_list(self())}]},
[])))
}
].
-endif.
| null | https://raw.githubusercontent.com/TensorWrench/lager_extras/74f15872b0562302b3cd08280c072ec5e6a03a88/src/lager_json_formatter.erl | erlang | Copyright 2012 Tensor Wrench LLC. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Include files
Exported Functions
API Functions
-record(lager_log_message,{
destinations,
metadata,
severity_as_int,
timestamp,
message
}). |
* Neither the name of TensorWrench , LLC nor the names of its
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(lager_json_formatter).
-include_lib("lager/include/lager.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-export([format/2]).
-spec format(#lager_log_message{},list()) -> iolist().
format(#lager_log_message{}=Message,Config) ->
Encoder=lager_extras_mochijson2:encoder([{handler,fun json_handler/1},{utf8,proplists:get_value(utf8,Config,true)}]),
Encoder(Message).
json_handler(#lager_log_message{message=Message,metadata=Metadata,timestamp={Date,Time},severity_as_int=Level}) ->
Severity=lager_util:num_to_level(Level),
{struct,[{date,list_to_binary(Date)},
{time,list_to_binary(Time)},
{severity,Severity},
{message,iolist_to_binary(Message)}
| [ {K,make_printable(V)} || {K,V} <- Metadata]]}.
make_printable(A) when is_atom(A) orelse is_binary(A) orelse is_number(A) -> A;
make_printable(P) when is_pid(P) -> iolist_to_binary(pid_to_list(P));
make_printable(Other) -> iolist_to_binary(io_lib:format("~p",[Other])).
-ifdef(TEST).
basic_test_() ->
[{"Just a plain message.",
?_assertEqual(iolist_to_binary(<<"{\"date\":\"Day\",\"time\":\"Time\",\"severity\":\"error\",\"message\":\"Message\"}">>),
iolist_to_binary(format(#lager_log_message{timestamp={"Day","Time"},
message="Message",
severity_as_int=lager_util:level_to_num(error),
metadata=[]},
[])))
},
{"Just a plain with standard metadata.",
?_assertEqual(iolist_to_binary([<<"{\"date\":\"Day\",\"time\":\"Time\",\"severity\":\"error\",\"message\":\"Message\"">>,
<<",\"module\":\"">>,atom_to_list(?MODULE),$",
<<",\"function\":\"my_function\"">>,
<<",\"line\":999">>,
<<",\"pid\":\"\\\"">>, pid_to_list(self()),<<"\\\"\"">>,
"}"
]),
iolist_to_binary(format(#lager_log_message{timestamp={"Day","Time"},
message="Message",
severity_as_int=lager_util:level_to_num(error),
metadata=[{module,?MODULE},{function,my_function},{line,999},{pid,pid_to_list(self())}]},
[])))
}
].
-endif.
|
b0e7b4c6056f8ee53e6f717d4eed4d4ec1fb5c72c803d3da6d5a8e59d4b8506e | smallmelon/sdzmmo | lib_pet.erl | %%%--------------------------------------
%%% @Module : lib_pet
@Author : shebiao
%%% @Email :
@Created : 2010.07.03
%%% @Description : 宠物信息
%%%--------------------------------------
-module(lib_pet).
-include("common.hrl").
-include("record.hrl").
-compile(export_all).
%%=========================================================================
%% SQL定义
%%=========================================================================
%% -----------------------------------------------------------------
%% 角色表SQL
%% -----------------------------------------------------------------
-define(SQL_PLAYER_UPDATE_DEDUCT_GOLD, "update player set gold = gold-~p where id = ~p").
-define(SQL_PLAYER_UPDATE_EXTENT_QUE, "update player set gold = gold-~p, pet_upgrade_que_num=~p where id = ~p").
-define(SQL_PLAYER_UPDATE_DEDUCT_COIN, "update player set coin = coin-~p where id=~p").
%% -----------------------------------------------------------------
宠物表SQL
%% -----------------------------------------------------------------
-define(SQL_PET_INSERT, "insert into pet(player_id,type_id,type_name,name,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,aptitude_threshold,strength, strength_daily, strength_threshold,create_time, strength_daily_nexttime) "
"values(~p,~p,'~s','~s',~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p, ~p)").
-define(SQL_PET_SELECT_ALL_PET, "select id,player_id,type_id,type_name,name,rename_count,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,base_forza_new,base_wit_new,base_agile_new,aptitude_forza,aptitude_wit,aptitude_agile,aptitude_threshold,attribute_shuffle_count,strength,strength_daily_nexttime,fight_flag,fight_icon_pos,upgrade_flag,upgrade_endtime,create_time,strength_threshold,strength_daily from pet where player_id=~p").
-define(SQL_PET_SELECT_INCUBATE_PET, "select id,player_id,type_id,type_name,name,rename_count,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,base_forza_new,base_wit_new,base_agile_new,aptitude_forza,aptitude_wit,aptitude_agile,aptitude_threshold,attribute_shuffle_count,strength,strength_daily_nexttime,fight_flag,fight_icon_pos,upgrade_flag,upgrade_endtime,create_time,strength_threshold,strength_daily from pet where player_id=~p and type_id=~p and create_time=~p order by id desc limit 1").
-define(SQL_PET_UPDATE_RENAME_INFO, "update pet set name = '~s', rename_count = rename_count+1 where id = ~p").
-define(SQL_PET_UPDATE_FIGHT_FLAG, "update pet set fight_flag = ~p, fight_icon_pos = ~p where id = ~p").
-define(SQL_PET_UPDATE_SHUTTLE_INFO, "update pet set attribute_shuffle_count=attribute_shuffle_count+1, base_forza_new=~p, base_wit_new=~p, base_agile_new = ~p where id = ~p").
-define(SQL_PET_UPDATE_USE_ATTRIBUTE, "update pet set forza=~p, wit=~p, agile=~p, base_forza=~p, base_wit=~p, base_agile=~p, base_forza_new=0, base_wit_new=0, base_agile_new =0 where id = ~p").
-define(SQL_PET_UPDATE_LEVEL, "update pet set level=~p, upgrade_flag=~p, upgrade_endtime=~p, forza=~p, wit=~p, agile=~p where id=~p").
-define(SQL_PET_UPDATE_UPGRADE_INFO, "update pet set upgrade_flag=~p, upgrade_endtime=~p where id=~p").
-define(SQL_PET_UPDATE_STRENGTH, "update pet set strength=~p,forza=~p, wit=~p, agile=~p where id=~p").
-define(SQL_PET_UPDATE_FORZA, "update pet set forza=~p, aptitude_forza=~p where id=~p").
-define(SQL_PET_UPDATE_WIT, "update pet set wit=~p, aptitude_wit=~p where id=~p").
-define(SQL_PET_UPDATE_AGILE, "update pet set agile=~p, aptitude_agile=~p where id=~p").
-define(SQL_PET_UPDATE_QUALITY, "update pet set quality=~p, aptitude_threshold=~p, level=~p where id=~p").
-define(SQL_PET_UPDATE_STRENGTH_DAILY, "update pet set strength=~p, forza=~p, wit=~p, agile=~p, strength_daily_nexttime=~p where id=~p").
-define(SQL_PET_UPDATE_LOGIN, "update pet set level=~p, upgrade_flag=~p, upgrade_endtime=~p, strength=~p, forza=~p, wit=~p, agile=~p, strength_daily_nexttime=~p where id=~p").
-define(SQL_PET_DELETE, "delete from pet where id = ~p").
-define(SQL_PET_DELETE_ROLE, "delete from pet where player_id = ~p").
%% -----------------------------------------------------------------
%% 宠物道具表SQL
%% -----------------------------------------------------------------
-define(SQL_BASE_PET_SELECT_ALL, "select goods_id, goods_name, name, probability from base_pet").
%%=========================================================================
%% 初始化回调函数
%%=========================================================================
%% -----------------------------------------------------------------
%% 系统启动后的加载
%% -----------------------------------------------------------------
load_base_pet() ->
SQL = io_lib:format(?SQL_BASE_PET_SELECT_ALL, []),
?DEBUG("load_base_pet: SQL=[~s]", [SQL]),
BasePetList = db_sql:get_all(SQL),
lists:map(fun load_base_pet_into_ets/1, BasePetList),
?DEBUG("load_base_pet: [~p] base_pet loaded", [length(BasePetList)]).
load_base_pet_into_ets([GoodsId,GoodsName,Name,Probability]) ->
BasePet = #ets_base_pet{
goods_id = GoodsId,
goods_name = GoodsName,
name = Name,
probability = Probability},
update_base_pet(BasePet).
%% -----------------------------------------------------------------
%% 登录后的初始化
%% -----------------------------------------------------------------
role_login(PlayerId) ->
?DEBUG("role_login: Loading pets...", []),
% 加载所有宠物
PetNum = load_all_pet(PlayerId),
FightingPet = get_fighting_pet(PlayerId),
?DEBUG("role_login: All pet num=[~p], fighting pet num=[~p]", [PetNum, length(FightingPet)]),
计算出战宠物的属性和
calc_pet_attribute_sum(FightingPet).
calc_pet_attribute_sum(Pets) ->
calc_pet_attribute_sum_helper(Pets, 0, 0, 0).
calc_pet_attribute_sum_helper([], TotalForza, TotalWit, TotalAgile) ->
[TotalForza, TotalWit, TotalAgile];
calc_pet_attribute_sum_helper(Pets, TotalForza, TotalWit, TotalAgile) ->
[Pet|PetLeft] = Pets,
calc_pet_attribute_sum_helper(PetLeft, TotalForza+Pet#ets_pet.forza_use, TotalWit+Pet#ets_pet.wit_use, TotalAgile+Pet#ets_pet.agile_use).
load_all_pet(PlayerId) ->
Data = [PlayerId],
SQL = io_lib:format(?SQL_PET_SELECT_ALL_PET, Data),
?DEBUG("load_all_pet: SQL=[~s]", [SQL]),
PetList = db_sql:get_all(SQL),
lists:map(fun load_pet_into_ets/1, PetList),
length(PetList).
load_pet_into_ets([Id,PlayerId,TypeId,TypeName,Name,RenameCount,Level,Quality,_Forza,_Wit,_Agile,BaseForza,BaseWit,BaseAgile,BaseForzaNew,BaseWitNew,BaseAgileNew,AptitudeForza,AptitudeWit,AptitudeAgile,AptitudeThreshold,AttributeShuffleCount,Strength,StrengthDailyNextTime,FightFlag,FightIconPos,UpgradeFlag,UpgradeEndTime,CreateTime,StrengthThreshold,StrengthDaily]) ->
1- 计算出战宠物的下次体力值同步时间
NowTime = util:unixtime(),
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
StrengthNextTime = case FightFlag of
0 -> 0;
1 -> NowTime+IntervalSync;
_ -> ?ERR("load_pet_into_ets: Unknow fight flag, flag=[~p]", FightFlag), 0
end,
2- 收取每日体力
[StrengthNew, StrengthDailyNextTimeNew] = calc_strength_daily(NowTime, StrengthDailyNextTime, Strength, StrengthDaily),
3- 升级完成检测
[LevelNew,UpgradeFlagNew,UpgradeEndTimeNew] = case is_upgrade_finish(UpgradeFlag, UpgradeEndTime) of
% 升级标志为真且已升完
true -> [Level+1, 0, 0];
% 其他情况
false -> [Level, UpgradeFlag,UpgradeEndTime]
end,
% 4- 重新计算属性值
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, LevelNew, StrengthNew),
[ForzaNew, WitNew, AgileNew] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
5-
if ((StrengthNew /= Strength) or (LevelNew > Level)) ->
SQLData = [LevelNew,UpgradeFlagNew,UpgradeEndTimeNew,StrengthNew, ForzaNew, WitNew, AgileNew, StrengthDailyNextTimeNew, Id],
SQL = io_lib:format(?SQL_PET_UPDATE_LOGIN, SQLData),
?DEBUG("load_pet_into_ets: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
true ->
void
end,
% 6- 插入缓存
Pet = #ets_pet{
id = Id,
player_id = PlayerId,
type_id = TypeId,
type_name = TypeName,
name = Name,
rename_count = RenameCount,
level = LevelNew,
quality = Quality,
forza = ForzaNew,
wit = WitNew,
agile = AgileNew,
base_forza = BaseForza,
base_wit = BaseWit,
base_agile = BaseAgile,
base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
aptitude_forza = AptitudeForza,
aptitude_wit = AptitudeWit,
aptitude_agile = AptitudeAgile,
aptitude_threshold = AptitudeThreshold,
attribute_shuffle_count = AttributeShuffleCount,
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew,
fight_flag = FightFlag,
fight_icon_pos = FightIconPos,
upgrade_flag = UpgradeFlagNew,
upgrade_endtime = UpgradeEndTimeNew,
create_time = CreateTime,
strength_threshold = StrengthThreshold,
strength_daily = StrengthDaily,
strength_nexttime = StrengthNextTime,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse},
update_pet(Pet).
%% -----------------------------------------------------------------
%% 退出后的存盘
%% -----------------------------------------------------------------
role_logout(PlayerId) ->
% 保存宠物数据
PetList = get_all_pet(PlayerId),
lists:map(fun save_pet/1, PetList),
删除所有缓存宠物
delete_all_pet(PlayerId).
save_pet(Pet) ->
Data = [Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
% ?DEBUG("save_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL).
%%=========================================================================
%% 业务操作函数
%%=========================================================================
%% -----------------------------------------------------------------
%% 孵化宠物
%% -----------------------------------------------------------------
incubate_pet(PlayerId, GoodsType) ->
?DEBUG("incubate_pet: PlayerId=[~p], GoodsTypeId=[~p]", [PlayerId, GoodsType#ets_goods_type.goods_id]),
解析物品类型
TypeId = GoodsType#ets_goods_type.goods_id,
%PetName = GoodsType#ets_goods_type.goods_name,
BasePet = get_base_pet(TypeId),
PetName = case BasePet of
[] -> ?ERR("incubate_pet: Not find the base_pet, goods_id=[~p]", [TypeId]),
make_sure_binary("我的宠物");
_ -> BasePet#ets_base_pet.name
end,
PetQuality = GoodsType#ets_goods_type.color,
% 获取配置
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [PetQuality]),
DefaultAptitude = data_pet:get_pet_config(default_aptitude, []),
DefaultLevel = data_pet:get_pet_config(default_level, []),
DefaultStrength = data_pet:get_pet_config(default_strenght, []),
StrengthThreshold = data_pet:get_pet_config(strength_threshold, []),
StrengthDaily = data_pet:get_pet_config(strength_daily, []),
% 随机获得基础属性
[BaseForza,BaseWit,BaseAgile] = generate_base_attribute(),
% 计算属性值
AptitudeAttributes = [DefaultAptitude,DefaultAptitude,DefaultAptitude],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, DefaultLevel, DefaultStrength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
插入宠物
CreateTime = util:unixtime(),
StrengthDailyNextTime = CreateTime+(?ONE_DAY_SECONDS),
Data = [PlayerId, TypeId, PetName, PetName, DefaultLevel] ++
[PetQuality, Forza, Wit, Agile, BaseForza, BaseWit, BaseAgile] ++
[AptitudeThreshold, DefaultStrength, StrengthDaily, StrengthThreshold, CreateTime, StrengthDailyNextTime],
SQL = io_lib:format(?SQL_PET_INSERT, Data),
?DEBUG("incubate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
获取新孵化的宠物
Data1 = [PlayerId, TypeId, CreateTime],
SQL1 = io_lib:format(?SQL_PET_SELECT_INCUBATE_PET, Data1),
?DEBUG("incubate_pet: SQL=[~s]", [SQL1]),
IncubateInfo = db_sql:get_row(SQL1),
case IncubateInfo of
% 孵化失败
[] ->
?ERR("incubate_pet: Failed to incubated pet, PlayerId=[~p], TypeId=[~p], CreateTime=[~p]", [PlayerId, TypeId, CreateTime]),
0;
% 孵化成功
_ ->
% 更新缓存
load_pet_into_ets(IncubateInfo),
% 返回值
[PetId| _] = IncubateInfo,
Pet = get_pet(PlayerId, PetId),
?DEBUG("incubate_pet: Cache was upate, PetId=[~p]", [Pet#ets_pet.id]),
[ok, PetId, PetName]
end.
%% -----------------------------------------------------------------
%% 宠物放生
%% -----------------------------------------------------------------
free_pet(PetId) ->
% 删除宠物
?DEBUG("free_pet: PetId=[~p]", [PetId]),
SQL = io_lib:format(?SQL_PET_DELETE, [PetId]),
?DEBUG("free_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
% 更新缓存
delete_pet(PetId),
ok.
%% -----------------------------------------------------------------
%% 宠物改名
%% -----------------------------------------------------------------
rename_pet(PetId, PetName, PlayerId, RenameMoney) ->
?DEBUG("rename_pet: PetId=[~p], PetName=[~p], PlayerId=[~p], ModifyMoney=[~p]", [PetId, PetName, PlayerId, RenameMoney]),
% 更新宠物名
Data = [PetName, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_RENAME_INFO, Data),
?DEBUG("rename_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
if RenameMoney > 0 ->
Data1 = [RenameMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("rename_pet: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
true ->
void
end,
ok.
%% -----------------------------------------------------------------
宠物出战
%% -----------------------------------------------------------------
fighting_pet(PetId, FightingPet, FightIconPos) ->
?DEBUG("fighting_pet: PetId=[~p], FightingPet=[~p], FightIconPos=[~p]", [PetId, FightingPet, FightIconPos]),
% 计算出战图标位置
IconPos = case FightIconPos of
0 -> calc_fight_icon_pos(FightingPet);
1 -> 1;
2 -> 2;
3 -> 3;
_ -> ?ERR("fighting_pet: Unknow fight icon pos = [~p]", [FightIconPos]), 0
end,
% 更新宠物
if ((IconPos >= 1) and (IconPos =< 3)) ->
Data = [1, IconPos, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("fighting_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, IconPos];
true ->
error
end.
calc_fight_icon_pos(FightingPet) ->
IconPosList = data_pet:get_pet_config(fight_icon_pos_list,[]),
FilteredIconPosList = filter_fight_icon_pos(FightingPet, IconPosList),
case length(FilteredIconPosList) of
0 -> 0;
_ -> lists:nth(1, FilteredIconPosList)
end.
filter_fight_icon_pos([], IconPosList) ->
IconPosList;
filter_fight_icon_pos(FightingPet, IconList) ->
[Pet|PetLeft] = FightingPet,
filter_fight_icon_pos(PetLeft, lists:delete(Pet#ets_pet.fight_icon_pos, IconList)).
%% -----------------------------------------------------------------
%% 宠物休息
%% -----------------------------------------------------------------
rest_pet(PetId) ->
?DEBUG("rest_pet: PetId=[~p]", [PetId]),
Data = [0, 0, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("rest_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
%% -----------------------------------------------------------------
%% 属性洗练
%% -----------------------------------------------------------------
shuffle_attribute(PlayerId, PetId, PayType, ShuffleCount, GoodsId, MoneyGoodsNum, MoneyGoodsUseNum) ->
?DEBUG("shuffle_attribute: PlayerId=[~p],PetId=[~p],PayType=[~p],ShuffleCount=[~p],GoodsId=[~p],MoneyGoodsNum=[~p],MoneyGoodsUseNum=[~p]", [PlayerId, PetId, PayType, ShuffleCount, GoodsId, MoneyGoodsNum, MoneyGoodsUseNum]),
% 生成新基础属性
[BaseForza, BaseWit, BaseAgile] = generate_base_attribute(ShuffleCount),
% 更新新基础属性和洗练次数
Data = [BaseForza, BaseWit, BaseAgile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_SHUTTLE_INFO, Data),
?DEBUG("shuffle_attribute: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
case PayType of
0 ->
% 扣取金币
Data1 = [MoneyGoodsUseNum, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("shuffle_attribute: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
_ ->
void
end,
[ok, BaseForza, BaseWit, BaseAgile].
%% -----------------------------------------------------------------
洗练属性使用
%% -----------------------------------------------------------------
use_attribute(PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Stength) ->
?DEBUG("use_attribute: PetId=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], Level=[~p], Stength=[~p]", [PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Stength]),
% 计算属性值
AptitudeAttributes = [AptitudeForza, AptitudeWit, AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, Stength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
?DEBUG("use_attribut: ForzaUse=[~p], WitUse=[~p], AgileUse=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [ForzaUse, WitUse, AgileUse, Forza, Wit, Agile]),
% 更新属性
Data = [Forza, Wit, Agile, BaseForza, BaseWit, BaseAgile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_USE_ATTRIBUTE, Data),
?DEBUG("use_attribute: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse].
%% -----------------------------------------------------------------
%% 宠物开始升级
%% -----------------------------------------------------------------
pet_start_upgrade(PlayerId, PetId, UpgradeEndTime, UpgradeMoney) ->
?DEBUG("pet_start_upgrade: PlayerId=[~p], PetId=[~p], UpgradeEndTime=[~p], UpgradeMoney=[~p]", [PlayerId, PetId, UpgradeEndTime, UpgradeMoney]),
% 更新升级信息
Data = [1, UpgradeEndTime, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("pet_start_upgrade: SQL=[~s]", [SQL]),
% 扣除铜币
db_sql:execute(SQL),
Data1 = [UpgradeMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_COIN, Data1),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
%% -----------------------------------------------------------------
%% 宠物升级加速
%% -----------------------------------------------------------------
shorten_upgrade(PlayerId, PetId, UpgradeEndTime, ShortenMoney) ->
?DEBUG("shorten_upgrade: PlayerId=[~p], PetId=[~p], UpgradeEndTime=[~p], ShortenMoney=[~p]", [PlayerId, PetId, UpgradeEndTime, ShortenMoney]),
% 更新升级信息
Data = [1, UpgradeEndTime, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
% 扣除金币
Data1 = [ShortenMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
%% -----------------------------------------------------------------
检查宠物升级状态
%% @return 不在升级:[0,升级剩余时间],
%% 还在升级:[1,升级剩余时间],
升完级 : [ 2,升级剩余时间 , 新级别,新力量,新智慧,新敏捷 , 新力量(加成用),新智慧(加成用),新敏捷(加成用 ) ]
%% -----------------------------------------------------------------
check_upgrade_state(PlayerId, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) ->
?DEBUG("check_upgrade_state: PlayerId=[~p], PetId=[~p], Level=[~p], Strength=[~p], UpgradeFlag=[~p], UpgradeEndTime=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p],UpgradeMoney=[~p]", [PlayerId, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney]),
case UpgradeFlag of
不在升级
0 ->
[0, 0];
在升级
1->
NowTime = util:unixtime(),
UpgradeInaccuracy = data_pet:get_pet_config(upgrade_inaccuracy, []),
UpgradeLeftTime = abs(UpgradeEndTime-NowTime),
if % 已经升完级
((NowTime >= UpgradeEndTime) or (UpgradeLeftTime < UpgradeInaccuracy)) ->
case pet_finish_upgrade(PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) of
[ok, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] -> [2, 0, NewLevel,NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse];
_ -> error
end;
% 还未升完级
true ->
[1, UpgradeLeftTime]
end
end.
%% -----------------------------------------------------------------
%% 宠物完成升级
%% -----------------------------------------------------------------
pet_finish_upgrade(PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) ->
?DEBUG("pet_finish_upgrade: PlayerId=[~p], PetId=[~p], Level=[~p], Strength=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p], UpgradeMoney=[~p]", [PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney]),
NewLevel = Level + 1,
% 计算属性值
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, NewLevel, Strength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
?DEBUG("pet_finish_upgrade: Level=[~p], NewLevel=[~p], ForzaUse=[~p], WitUse=[~p], AgileUse=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [Level, NewLevel, ForzaUse, WitUse, AgileUse, Forza, Wit, Agile]),
% 更新宠物信息
UpgradeFlag = 0,
UpgradeEndTime = 0,
Data = [NewLevel, UpgradeFlag, UpgradeEndTime, Forza, Wit, Agile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_LEVEL, Data),
?DEBUG("pet_finish_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
if % 扣取金币
UpgradeMoney > 0 ->
Data1 = [UpgradeMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("pet_finish_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
true ->
void
end,
[ok, NewLevel, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse].
%% -----------------------------------------------------------------
%% 扩展升级队列
%% -----------------------------------------------------------------
extent_upgrade_que(PlayerId, NewQueNum, ExtentQueMoney) ->
Data = [ExtentQueMoney, NewQueNum, PlayerId],
SQL = io_lib:format(?SQL_PLAYER_UPDATE_EXTENT_QUE, Data),
?DEBUG("extent_upgrade_que: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
%% -----------------------------------------------------------------
%% 喂养宠物
%% -----------------------------------------------------------------
feed_pet(PetId, PetQuality, FoodQuality, GoodsUseNum, Strength, StrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) ->
?DEBUG("feed_pet: PetId=[~p], PetQuality=[~p], FoodQuality=[~p], GoodsUseNum=[~p], Strength=[~p], PetStrengThreshold=[~p]", [PetId, PetQuality, FoodQuality, GoodsUseNum, Strength, StrengThreshold]),
% 计算增加的体力
FoodStrength = data_pet:get_food_strength(PetQuality, FoodQuality),
StrengthTotal = Strength+GoodsUseNum*FoodStrength,
StrengthNew = case StrengthTotal >= StrengThreshold of
true -> StrengThreshold;
false -> StrengthTotal
end,
% 体力值变化影响了力智敏则重新计算属性值
case is_strength_add_change_attribute(Strength, StrengthNew) of
true ->
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, StrengthNew),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
% 更新体力值和属性
Data = [StrengthNew, Forza, Wit, Agile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("feed_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, StrengthNew, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse];
false ->
[ok, StrengthNew]
end.
%% -----------------------------------------------------------------
%% 驯养宠物
%% -----------------------------------------------------------------
domesticate_pet(PetId, DomesticateType, Level, Strength, Aptitude, AptitudeThreshold, BaseAttribute) ->
?DEBUG("domesticate_pet: PetId=[~p], DomesticateType=[~p], Level=[~p], Strength=[~p], Aptitude=[~p], AptitudeThreshold=[~p], BaseAttribute=[~p]", [PetId, DomesticateType, Level, Strength, Aptitude, AptitudeThreshold, BaseAttribute]),
AptitudeValid = case Aptitude > AptitudeThreshold of
true -> AptitudeThreshold;
false -> Aptitude
end,
[AttributeUse] = calc_pet_attribute([AptitudeValid], [BaseAttribute], Level, Strength),
[Attribute] = calc_pet_client_attribute([AttributeUse]),
case DomesticateType of
0 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FORZA, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
1 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_WIT, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
2 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_AGILE, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end,
[ok, AptitudeValid, Attribute, AttributeUse].
%% -----------------------------------------------------------------
宠物进阶
%% -----------------------------------------------------------------
enhance_quality(PetId, Quality, SuccessProbability) ->
?DEBUG("enhance_quality: PetId=[~p], Quality=[~p], SuccessProbability=[~p]", [PetId, Quality, SuccessProbability]),
case get_enhance_quality_result(SuccessProbability) of
% 进阶成功
true ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [Quality+1]),
Data1 = [Quality+1, AptitudeThreshold, 1, PetId],
SQL1 = io_lib:format(?SQL_PET_UPDATE_QUALITY, Data1),
?DEBUG("enhance_quality: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
[ok, 1, Quality+1, AptitudeThreshold];
% 进阶失败
false ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [Quality]),
[ok, 0, Quality, AptitudeThreshold]
end.
%% -----------------------------------------------------------------
%% 体力值同步
%% -----------------------------------------------------------------
strength_sync([], _NowTime, RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile) ->
[RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile];
strength_sync(Pets, NowTime, RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile) ->
[Pet|PetLeft] = Pets,
if % 同步时间到达
NowTime >= Pet#ets_pet.strength_nexttime ->
% 计算新的体力值
[IntervalSync, StrengthSync] = data_pet:get_pet_config(strength_sync, []),
StrengthNew = case Pet#ets_pet.strength > StrengthSync of
true -> Pet#ets_pet.strength-StrengthSync;
false -> 0
end,
?DEBUG("strength_sync: Time arrive, PlayeId=[~p], PetId=[~p], Strength=[~p], StrengthNew=[~p]", [Pet#ets_pet.player_id, Pet#ets_pet.id,Pet#ets_pet.strength, StrengthNew]),
% 判断体力值变化是否影响力智敏
PetId = Pet#ets_pet.id,
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
% 重新计算力智敏
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
% 更新缓存
PetNew = Pet#ets_pet{
strength_nexttime = NowTime+IntervalSync,
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew},
update_pet(PetNew),
% 更新数据库
SQLData = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, SQLData),
?DEBUG("strength_sync: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
% 继续循环
Data = <<PetId:32,StrengthNew:16,1:16, Forza:16, Wit:16, Agile:16>>,
strength_sync(PetLeft, NowTime, RecordsNum+1, list_to_binary([RecordsData, Data]), TotalForza+ForzaUse, TotalWit+WitUse, TotalAgile+AgileUse);
false ->
% 更新缓存
PetNew = Pet#ets_pet{
strength_nexttime = NowTime+IntervalSync,
strength = StrengthNew},
update_pet(PetNew),
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
ForzaUse = Pet#ets_pet.forza_use,
WitUse = Pet#ets_pet.wit_use,
AgileUse = Pet#ets_pet.agile_use,
% 继续循环
Data = <<PetId:32,StrengthNew:16,0:16, Forza:16, Wit:16, Agile:16>>,
strength_sync(PetLeft, NowTime, RecordsNum+1, list_to_binary([RecordsData, Data]), TotalForza+ForzaUse, TotalWit+WitUse, TotalAgile+AgileUse)
end;
% 同步时间未到
true ->
?DEBUG("strength_sync: Not this time, PlayeId=[~p], PetId=[~p], Strength=[~p]", [Pet#ets_pet.player_id, Pet#ets_pet.id,Pet#ets_pet.strength]),
strength_sync(PetLeft, NowTime, RecordsNum, RecordsData, TotalForza+Pet#ets_pet.forza_use, TotalWit+Pet#ets_pet.wit_use, TotalAgile+Pet#ets_pet.agile_use)
end.
%% -----------------------------------------------------------------
%% 获取宠物信息
%% -----------------------------------------------------------------
get_pet_info(PetId) ->
?DEBUG("get_pet_info: PetId=[~p]", [PetId]),
Pet = get_pet(PetId),
宠物不存在
Pet =:= [] ->
[1, <<>>];
true ->
PetBin = parse_pet_info(Pet),
[1, PetBin]
end.
parse_pet_info(Pet) ->
[Id,Name,RenameCount,Level,Strength,Quality,Forza,Wit,Agile,BaseForza,BaseWit,BaseAgile,BaseForzaNew,BaseWitNew,BaseAgileNew,AptitudeForza,AptitudeWit,AptitudeAgile,AptitudeThreshold,Strength,FightFlag,UpgradeFlag,UpgradeEndtime,FightIconPos, StrengthThreshold, TypeId] =
[Pet#ets_pet.id, Pet#ets_pet.name, Pet#ets_pet.rename_count, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.base_forza_new, Pet#ets_pet.base_wit_new, Pet#ets_pet.base_agile_new, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.aptitude_threshold, Pet#ets_pet.strength, Pet#ets_pet.fight_flag, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime, Pet#ets_pet.fight_icon_pos, Pet#ets_pet.strength_threshold, Pet#ets_pet.type_id],
NameLen = byte_size(Name),
NowTime = util:unixtime(),
UpgradeLeftTime = case UpgradeFlag of
0 -> 0;
1 -> UpgradeEndtime - NowTime;
_ -> ?ERR("parse_pet_info: Unknow upgrade flag = [~p]", [UpgradeFlag])
end,
<<Id:32,NameLen:16,Name/binary,RenameCount:16,Level:16,Quality:16,Forza:16,Wit:16,Agile:16,BaseForza:16,BaseWit:16,BaseAgile:16,BaseForzaNew:16,BaseWitNew:16,BaseAgileNew:16,AptitudeForza:16,AptitudeWit:16,AptitudeAgile:16,AptitudeThreshold:16,Strength:16,FightFlag:16,UpgradeFlag:16,UpgradeLeftTime:32,FightIconPos:16,StrengthThreshold:16, TypeId:32>>.
%% -----------------------------------------------------------------
%% 获取宠物列表
%% -----------------------------------------------------------------
get_pet_list(PlayerId) ->
PetList = get_all_pet(PlayerId),
RecordNum = length(PetList),
if % 没有宠物
RecordNum == 0 ->
[1, RecordNum, <<>>];
true ->
Records = lists:map(fun parse_pet_info/1, PetList),
[1, RecordNum, list_to_binary(Records)]
end.
%% -----------------------------------------------------------------
%% 宠物出战替换
%% -----------------------------------------------------------------
fighting_replace(PetId, ReplacedPetId, IconPos) ->
?DEBUG("fighting_replace: PetId=[~p], ReplacedPetId=[~p], IconPos=[~p]", [PetId, ReplacedPetId, IconPos]),
Data = [1, IconPos, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("fighting_replace: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
Data1 = [0, 0, ReplacedPetId],
SQL1 = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data1),
?DEBUG("fighting_replace: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
%% -----------------------------------------------------------------
%% 取消升级
%% -----------------------------------------------------------------
cancel_upgrade(PetId) ->
?DEBUG("cancel_upgrade: PetId=[~p]", [PetId]),
Data = [0, 0, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("cancel_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
%% -----------------------------------------------------------------
%% 角色死亡扣减
%% -----------------------------------------------------------------
handle_role_dead(Status) ->
FightingPet = lib_pet:get_fighting_pet(Status#player_status.id),
lists:map(fun handle_pet_dead/1, FightingPet),
if length(FightingPet) > 0 ->
{ok, Bin} = pt_41:write(41000, [0]),
lib_send:send_one(Status#player_status.socket, Bin);
true ->
void
end.
handle_pet_dead(Pet) ->
计算扣取的体力值
DeadStrength = data_pet:get_pet_config(role_dead_strength, []),
StrengthNew = case Pet#ets_pet.strength > DeadStrength of
true -> (Pet#ets_pet.strength - DeadStrength);
false -> 0
end,
% 更新缓存
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
% 重新计算力智敏
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
% 更新缓存
PetNew = Pet#ets_pet{
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew},
update_pet(PetNew),
% 更新数据库
Data = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("handle_pet_dead: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
false ->
% 更新缓存
PetNew = Pet#ets_pet{strength = StrengthNew},
update_pet(PetNew),
% 更新数据库
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
Data = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("handle_pet_dead: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end.
%%=========================================================================
%% 定时服务
%%=========================================================================
%% -----------------------------------------------------------------
处理每日体力
%% -----------------------------------------------------------------
handle_daily_strength() ->
send_to_all('pet_strength_daily', []),
ok.
collect_strength_daily(Pet) ->
判断是否应该收取
NowTime = util:unixtime(),
[StrengthNew, StrengthDailyNextTimeNew] = calc_strength_daily(NowTime, Pet#ets_pet.strength_daily_nexttime, Pet#ets_pet.strength, Pet#ets_pet.strength_daily),
% 如果需要收取则进行
if StrengthNew /= Pet#ets_pet.strength ->
% 更新缓存
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
% 重新计算力智敏
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
% 更新缓存
PetNew = Pet#ets_pet{
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew},
update_pet(PetNew),
% 更新数据库
Data = [StrengthNew, Forza, Wit, Agile, StrengthDailyNextTimeNew, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH_DAILY, Data),
?DEBUG("collect_strength_daily: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
false ->
% 更新缓存
PetNew = Pet#ets_pet{
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew},
update_pet(PetNew),
% 更新数据库
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
Data = [StrengthNew, Forza, Wit, Agile, StrengthDailyNextTimeNew, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH_DAILY, Data),
?DEBUG("collect_strength_daily: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end;
true ->
void
end.
%% -----------------------------------------------------------------
%% 删除角色
%% -----------------------------------------------------------------
delete_role(PlayerId) ->
?DEBUG("delete_role: PlayerId=[~p]", [PlayerId]),
% 删除宠物表记录
Data = [PlayerId],
SQL = io_lib:format(?SQL_PET_DELETE_ROLE, Data),
?DEBUG("delete_role: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
% 删除缓存
delete_all_pet(PlayerId),
ok.
%%=========================================================================
%% 工具函数
%%=========================================================================
%% -----------------------------------------------------------------
%% 确保字符串类型为二进制
%% -----------------------------------------------------------------
make_sure_binary(String) ->
case is_binary(String) of
true -> String;
false when is_list(String) -> list_to_binary(String);
false ->
?ERR("make_sure_binary: Error string=[~w]", [String]),
String
end.
%% -----------------------------------------------------------------
%% 广播消息给进程
%% -----------------------------------------------------------------
send_to_all(MsgType, Bin) ->
Pids = ets:match(?ETS_ONLINE, #ets_online{pid='$1', _='_'}),
F = fun([P]) ->
gen_server:cast(P, {MsgType, Bin})
end,
[F(Pid) || Pid <- Pids].
%% -----------------------------------------------------------------
%% 根据1970年以来的秒数获得日期
%% -----------------------------------------------------------------
seconds_to_localtime(Seconds) ->
DateTime = calendar:gregorian_seconds_to_datetime(Seconds+?DIFF_SECONDS_0000_1900),
calendar:universal_time_to_local_time(DateTime).
%% -----------------------------------------------------------------
判断是否同一天
%% -----------------------------------------------------------------
is_same_date(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, _Time1} = seconds_to_localtime(Seconds1),
{{Year2, Month2, Day2}, _Time2} = seconds_to_localtime(Seconds2),
if ((Year1 /= Year2) or (Month1 /= Month2) or (Day1 /= Day2)) -> false;
true -> true
end.
%% -----------------------------------------------------------------
%% 判断是否同一星期
%% -----------------------------------------------------------------
is_same_week(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, Time1} = seconds_to_localtime(Seconds1),
星期几
Week1 = calendar:day_of_the_week(Year1, Month1, Day1),
% 从午夜到现在的秒数
Diff1 = calendar:time_to_seconds(Time1),
Monday = Seconds1 - Diff1 - (Week1-1)*?ONE_DAY_SECONDS,
Sunday = Seconds1 + (?ONE_DAY_SECONDS-Diff1) + (7-Week1)*?ONE_DAY_SECONDS,
if ((Seconds2 >= Monday) and (Seconds2 < Sunday)) -> true;
true -> false
end.
%% -----------------------------------------------------------------
%% 获取当天0点和第二天0点
%% -----------------------------------------------------------------
get_midnight_seconds(Seconds) ->
{{_Year, _Month, _Day}, Time} = seconds_to_localtime(Seconds),
% 从午夜到现在的秒数
Diff = calendar:time_to_seconds(Time),
% 获取当天0点
Today = Seconds - Diff,
% 获取第二天0点
NextDay = Seconds + (?ONE_DAY_SECONDS-Diff),
{Today, NextDay}.
%% -----------------------------------------------------------------
%% 计算相差的天数
%% -----------------------------------------------------------------
get_diff_days(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, _} = seconds_to_localtime(Seconds1),
{{Year2, Month2, Day2}, _} = seconds_to_localtime(Seconds2),
Days1 = calendar:date_to_gregorian_days(Year1, Month1, Day1),
Days2 = calendar:date_to_gregorian_days(Year2, Month2, Day2),
DiffDays=abs(Days2-Days1),
DiffDays+1.
%% -----------------------------------------------------------------
%% 随机生成基础属性
%% -----------------------------------------------------------------
generate_base_attribute() ->
% 获取配置
BaseAttributeSum = data_pet:get_pet_config(base_attribute_sum, []),
BaseForza = util:rand(1, BaseAttributeSum - 2),
BaseWit = util:rand(1, BaseAttributeSum - BaseForza - 1),
BaseAgile = BaseAttributeSum - BaseForza - BaseWit,
[BaseForza, BaseWit, BaseAgile].
generate_base_attribute(ShuffleCount) ->
% 获取配置
LuckyShuffleCount = data_pet:get_pet_config(lucky_shuffle_count, []),
if ShuffleCount >= LuckyShuffleCount ->
generate_base_attribute_lucky();
true ->
generate_base_attribute()
end.
generate_base_attribute_lucky() ->
% 获取配置
BaseAttributeSum = data_pet:get_pet_config(base_attribute_sum, []),
LuckyBaseAttribute = data_pet:get_pet_config(lucky_base_attribute, []),
LeftAttribute = BaseAttributeSum-LuckyBaseAttribute,
BaseForza = util:rand(1, LeftAttribute-2),
BaseWit = util:rand(1, LeftAttribute-BaseForza-1),
BaseAgile = LeftAttribute-BaseForza-BaseWit,
Index = util:rand(1, 3),
if Index == 1 ->
[BaseForza+LuckyBaseAttribute,BaseWit,BaseAgile];
Index == 2 ->
[BaseForza,BaseWit+LuckyBaseAttribute,BaseAgile];
Index == 3 ->
[BaseForza,BaseWit,BaseAgile+LuckyBaseAttribute]
end.
%% -----------------------------------------------------------------
%% 计算宠物属性
%% -----------------------------------------------------------------
calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, Strength) ->
calc_pet_attribute_helper(AptitudeAttributes, BaseAttributes, Level, Strength, []).
calc_pet_attribute_helper([], [], _Level, _Strength, Attributes) ->
Attributes;
calc_pet_attribute_helper(AptitudeAttributes, BaseAttributes, Level, Strength, Attributes) ->
[AptitudeAttribute|AptitudeAttributeLeft] = AptitudeAttributes,
[BaseAttribute|BaseAttributeLeft] = BaseAttributes,
0.1+(当前资质/100+基础值)*(当前等级-1)*0.0049
Attribute = 0.1 + (AptitudeAttribute/100+BaseAttribute)*(Level-1)*0.0049,
if Strength =< 0 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[0]);
Strength =< 50 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute*0.5]);
Strength =< 90 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute]);
true ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute*1.2])
end.
calc_pet_client_attribute(Attributes)->
calc_pet_client_attribute_helper(Attributes, []).
calc_pet_client_attribute_helper([], ClientAttributes) ->
ClientAttributes;
calc_pet_client_attribute_helper(Attributes, ClientAttributes) ->
[Attribute|AttributeLeft] = Attributes,
NewAttribute = round(Attribute*10),
calc_pet_client_attribute_helper(AttributeLeft, ClientAttributes++[NewAttribute]).
%% -----------------------------------------------------------------
计算宠物属性加点到角色的影响
%% -----------------------------------------------------------------
calc_player_attribute(Type, Status, Forza, Wit, Agile) ->
?DEBUG("calc_player_attribute:Type=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [Type, Forza, Wit, Agile]),
% 计算新的宠物力智敏
[NewPetForza, NewPetWit, NewPetAgile] = case Type of
add ->
[PetForza, PetWit, PetAgile] = Status#player_status.pet_attribute,
[PetForza+Forza, PetWit+Wit, PetAgile+Agile];
deduct ->
[PetForza, PetWit, PetAgile] = Status#player_status.pet_attribute,
[PetForza-Forza, PetWit-Wit, PetAgile-Agile];
replace -> [Forza, Wit, Agile]
end,
% 重新计算人物属性
Status1 = Status#player_status{pet_attribute = [NewPetForza,NewPetWit,NewPetAgile]},
Status2 = lib_player:count_player_attribute(Status1),
% 内息上限有变化则通知客户端
if Status1#player_status.hp_lim =/= Status2#player_status.hp_lim ->
{ok, SceneData} = pt_12:write(12009, [Status#player_status.id, Status2#player_status.hp, Status2#player_status.hp_lim]),
lib_send:send_to_area_scene(Status2#player_status.scene, Status2#player_status.x, Status2#player_status.y, SceneData);
true ->
void
end,
% 通知客户端角色属性改变
lib_player:send_attribute_change_notify(Status2, 1),
Status2.
calc_new_hp_mp(HpMp, HpMpLimit, HpMpLimitNew) ->
case HpMpLimit =/= HpMpLimitNew of
true ->
case HpMp > HpMpLimitNew of
true -> HpMpLimitNew;
false -> HpMp
end;
false ->
HpMp
end.
%% -----------------------------------------------------------------
计算升级加速所需金币
%% -----------------------------------------------------------------
calc_shorten_money(ShortenTime) ->
[MoneyUnit, Unit] = data_pet:get_pet_config(shorten_money_unit,[]),
TotalUnit = util:ceil(ShortenTime/Unit),
MoneyUnit * TotalUnit.
%% -----------------------------------------------------------------
%% 计算收取的每日体力值
%% -----------------------------------------------------------------
calc_strength_daily(NowTime, StrengthDailyNextTime, Strength, StrengthDaily) ->
{_Today, NextDay} = get_midnight_seconds(NowTime),
if % 小于第二天凌晨的应该收取
StrengthDailyNextTime =< NextDay ->
DiffDays = get_diff_days(StrengthDailyNextTime, NowTime),
StrengthTotal = StrengthDaily*DiffDays,
StrengthNew = case Strength > StrengthTotal of
true -> Strength - StrengthTotal;
false -> 0
end,
StrengthDailyNextTimeNew = NowTime+(?ONE_DAY_SECONDS),
[StrengthNew, StrengthDailyNextTimeNew];
% 不应该收取
true ->
[Strength, StrengthDailyNextTime]
end.
%% -----------------------------------------------------------------
%% -----------------------------------------------------------------
is_upgrade_finish(UpgradeFlag, UpgradeEndTime) ->
case UpgradeFlag of
不在升级
0 ->
false;
在升级
1->
NowTime = util:unixtime(),
UpgradeInaccuracy = data_pet:get_pet_config(upgrade_inaccuracy, []),
UpgradeLeftTime = abs(UpgradeEndTime-NowTime),
if % 已经升完级
((NowTime >= UpgradeEndTime) or (UpgradeLeftTime < UpgradeInaccuracy)) -> true;
% 还未升完级
true -> false
end
end.
%% -----------------------------------------------------------------
%% 判断体力值扣减是否改变角色属性
%% -----------------------------------------------------------------
is_strength_deduct_change_attribute(Strength, StrengthNew) ->
if ((StrengthNew == 0) and (Strength > 0)) -> true;
((StrengthNew =< 50) and (Strength > 50)) -> true;
((StrengthNew =< 90) and (Strength > 90)) -> true;
true -> false
end.
%% -----------------------------------------------------------------
判断体力值增加是否改变角色属性
%% -----------------------------------------------------------------
is_strength_add_change_attribute(Strength, StrengthNew) ->
if ((Strength =< 90) and (StrengthNew > 90)) -> true;
((Strength =< 50) and (StrengthNew > 50)) -> true;
((Strength == 0) and (StrengthNew > 0)) -> true;
true -> false
end.
%% -----------------------------------------------------------------
%% 根据成功几率获得进阶结果
%% -----------------------------------------------------------------
get_enhance_quality_result(SuccessProbability) ->
RandNumer = util:rand(1, 100),
if (RandNumer > SuccessProbability) -> false;
true -> true
end.
%%=========================================================================
缓存操作函数
%%=========================================================================
%% -----------------------------------------------------------------
通用函数
%% -----------------------------------------------------------------
lookup_one(Table, Key) ->
Record = ets:lookup(Table, Key),
if Record =:= [] ->
[];
true ->
[R] = Record,
R
end.
lookup_all(Table, Key) ->
ets:lookup(Table, Key).
match_one(Table, Pattern) ->
Record = ets:match_object(Table, Pattern),
if Record =:= [] ->
[];
true ->
[R] = Record,
R
end.
match_all(Table, Pattern) ->
ets:match_object(Table, Pattern).
%% -----------------------------------------------------------------
%% 宠物操作
%% -----------------------------------------------------------------
get_fighting_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, fight_flag=1, _='_'}).
get_pet(PlayerId, PetId) ->
match_one(?ETS_PET, #ets_pet{id=PetId, player_id=PlayerId, _='_'}).
get_pet(PetId) ->
lookup_one(?ETS_PET, PetId).
get_all_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, _='_'}).
get_pet_count(PlayerId) ->
length(get_all_pet(PlayerId)).
get_upgrading_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, upgrade_flag=1, _='_'}).
update_pet(Pet) ->
ets:insert(?ETS_PET, Pet).
delete_pet(PetId) ->
ets:delete(?ETS_PET, PetId).
delete_all_pet(PlayerId) ->
ets:match_delete(?ETS_PET, #ets_pet{player_id=PlayerId, _='_'}).
%% -----------------------------------------------------------------
%% 宠物道具
%% -----------------------------------------------------------------
get_base_pet(GoodsId) ->
lookup_one(?ETS_BASE_PET, GoodsId).
update_base_pet(BasePet) ->
ets:insert(?ETS_BASE_PET, BasePet).
%% -----------------------------------------------------------------
%% 背包物品
%% -----------------------------------------------------------------
get_goods(GoodsId) ->
match_one(?ETS_GOODS_ONLINE, #goods{id=GoodsId, location=4, _='_'}).
%% -----------------------------------------------------------------
%% 物品类型
%% -----------------------------------------------------------------
get_goods_type(GoodsId) ->
lookup_one(?ETS_GOODS_TYPE,GoodsId).
| null | https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/lib/lib_pet.erl | erlang | --------------------------------------
@Module : lib_pet
@Email :
@Description : 宠物信息
--------------------------------------
=========================================================================
SQL定义
=========================================================================
-----------------------------------------------------------------
角色表SQL
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物道具表SQL
-----------------------------------------------------------------
=========================================================================
初始化回调函数
=========================================================================
-----------------------------------------------------------------
系统启动后的加载
-----------------------------------------------------------------
-----------------------------------------------------------------
登录后的初始化
-----------------------------------------------------------------
加载所有宠物
升级标志为真且已升完
其他情况
4- 重新计算属性值
6- 插入缓存
-----------------------------------------------------------------
退出后的存盘
-----------------------------------------------------------------
保存宠物数据
?DEBUG("save_pet: SQL=[~s]", [SQL]),
=========================================================================
业务操作函数
=========================================================================
-----------------------------------------------------------------
孵化宠物
-----------------------------------------------------------------
PetName = GoodsType#ets_goods_type.goods_name,
获取配置
随机获得基础属性
计算属性值
孵化失败
孵化成功
更新缓存
返回值
-----------------------------------------------------------------
宠物放生
-----------------------------------------------------------------
删除宠物
更新缓存
-----------------------------------------------------------------
宠物改名
-----------------------------------------------------------------
更新宠物名
-----------------------------------------------------------------
-----------------------------------------------------------------
计算出战图标位置
更新宠物
-----------------------------------------------------------------
宠物休息
-----------------------------------------------------------------
-----------------------------------------------------------------
属性洗练
-----------------------------------------------------------------
生成新基础属性
更新新基础属性和洗练次数
扣取金币
-----------------------------------------------------------------
-----------------------------------------------------------------
计算属性值
更新属性
-----------------------------------------------------------------
宠物开始升级
-----------------------------------------------------------------
更新升级信息
扣除铜币
-----------------------------------------------------------------
宠物升级加速
-----------------------------------------------------------------
更新升级信息
扣除金币
-----------------------------------------------------------------
@return 不在升级:[0,升级剩余时间],
还在升级:[1,升级剩余时间],
-----------------------------------------------------------------
已经升完级
还未升完级
-----------------------------------------------------------------
宠物完成升级
-----------------------------------------------------------------
计算属性值
更新宠物信息
扣取金币
-----------------------------------------------------------------
扩展升级队列
-----------------------------------------------------------------
-----------------------------------------------------------------
喂养宠物
-----------------------------------------------------------------
计算增加的体力
体力值变化影响了力智敏则重新计算属性值
更新体力值和属性
-----------------------------------------------------------------
驯养宠物
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
进阶成功
进阶失败
-----------------------------------------------------------------
体力值同步
-----------------------------------------------------------------
同步时间到达
计算新的体力值
判断体力值变化是否影响力智敏
重新计算力智敏
更新缓存
更新数据库
继续循环
更新缓存
继续循环
同步时间未到
-----------------------------------------------------------------
获取宠物信息
-----------------------------------------------------------------
-----------------------------------------------------------------
获取宠物列表
-----------------------------------------------------------------
没有宠物
-----------------------------------------------------------------
宠物出战替换
-----------------------------------------------------------------
-----------------------------------------------------------------
取消升级
-----------------------------------------------------------------
-----------------------------------------------------------------
角色死亡扣减
-----------------------------------------------------------------
更新缓存
重新计算力智敏
更新缓存
更新数据库
更新缓存
更新数据库
=========================================================================
定时服务
=========================================================================
-----------------------------------------------------------------
-----------------------------------------------------------------
如果需要收取则进行
更新缓存
重新计算力智敏
更新缓存
更新数据库
更新缓存
更新数据库
-----------------------------------------------------------------
删除角色
-----------------------------------------------------------------
删除宠物表记录
删除缓存
=========================================================================
工具函数
=========================================================================
-----------------------------------------------------------------
确保字符串类型为二进制
-----------------------------------------------------------------
-----------------------------------------------------------------
广播消息给进程
-----------------------------------------------------------------
-----------------------------------------------------------------
根据1970年以来的秒数获得日期
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
判断是否同一星期
-----------------------------------------------------------------
从午夜到现在的秒数
-----------------------------------------------------------------
获取当天0点和第二天0点
-----------------------------------------------------------------
从午夜到现在的秒数
获取当天0点
获取第二天0点
-----------------------------------------------------------------
计算相差的天数
-----------------------------------------------------------------
-----------------------------------------------------------------
随机生成基础属性
-----------------------------------------------------------------
获取配置
获取配置
获取配置
-----------------------------------------------------------------
计算宠物属性
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
计算新的宠物力智敏
重新计算人物属性
内息上限有变化则通知客户端
通知客户端角色属性改变
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
计算收取的每日体力值
-----------------------------------------------------------------
小于第二天凌晨的应该收取
不应该收取
-----------------------------------------------------------------
-----------------------------------------------------------------
已经升完级
还未升完级
-----------------------------------------------------------------
判断体力值扣减是否改变角色属性
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
根据成功几率获得进阶结果
-----------------------------------------------------------------
=========================================================================
=========================================================================
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物操作
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物道具
-----------------------------------------------------------------
-----------------------------------------------------------------
背包物品
-----------------------------------------------------------------
-----------------------------------------------------------------
物品类型
-----------------------------------------------------------------
| @Author : shebiao
@Created : 2010.07.03
-module(lib_pet).
-include("common.hrl").
-include("record.hrl").
-compile(export_all).
-define(SQL_PLAYER_UPDATE_DEDUCT_GOLD, "update player set gold = gold-~p where id = ~p").
-define(SQL_PLAYER_UPDATE_EXTENT_QUE, "update player set gold = gold-~p, pet_upgrade_que_num=~p where id = ~p").
-define(SQL_PLAYER_UPDATE_DEDUCT_COIN, "update player set coin = coin-~p where id=~p").
宠物表SQL
-define(SQL_PET_INSERT, "insert into pet(player_id,type_id,type_name,name,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,aptitude_threshold,strength, strength_daily, strength_threshold,create_time, strength_daily_nexttime) "
"values(~p,~p,'~s','~s',~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p,~p, ~p)").
-define(SQL_PET_SELECT_ALL_PET, "select id,player_id,type_id,type_name,name,rename_count,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,base_forza_new,base_wit_new,base_agile_new,aptitude_forza,aptitude_wit,aptitude_agile,aptitude_threshold,attribute_shuffle_count,strength,strength_daily_nexttime,fight_flag,fight_icon_pos,upgrade_flag,upgrade_endtime,create_time,strength_threshold,strength_daily from pet where player_id=~p").
-define(SQL_PET_SELECT_INCUBATE_PET, "select id,player_id,type_id,type_name,name,rename_count,level,quality,forza,wit,agile,base_forza,base_wit,base_agile,base_forza_new,base_wit_new,base_agile_new,aptitude_forza,aptitude_wit,aptitude_agile,aptitude_threshold,attribute_shuffle_count,strength,strength_daily_nexttime,fight_flag,fight_icon_pos,upgrade_flag,upgrade_endtime,create_time,strength_threshold,strength_daily from pet where player_id=~p and type_id=~p and create_time=~p order by id desc limit 1").
-define(SQL_PET_UPDATE_RENAME_INFO, "update pet set name = '~s', rename_count = rename_count+1 where id = ~p").
-define(SQL_PET_UPDATE_FIGHT_FLAG, "update pet set fight_flag = ~p, fight_icon_pos = ~p where id = ~p").
-define(SQL_PET_UPDATE_SHUTTLE_INFO, "update pet set attribute_shuffle_count=attribute_shuffle_count+1, base_forza_new=~p, base_wit_new=~p, base_agile_new = ~p where id = ~p").
-define(SQL_PET_UPDATE_USE_ATTRIBUTE, "update pet set forza=~p, wit=~p, agile=~p, base_forza=~p, base_wit=~p, base_agile=~p, base_forza_new=0, base_wit_new=0, base_agile_new =0 where id = ~p").
-define(SQL_PET_UPDATE_LEVEL, "update pet set level=~p, upgrade_flag=~p, upgrade_endtime=~p, forza=~p, wit=~p, agile=~p where id=~p").
-define(SQL_PET_UPDATE_UPGRADE_INFO, "update pet set upgrade_flag=~p, upgrade_endtime=~p where id=~p").
-define(SQL_PET_UPDATE_STRENGTH, "update pet set strength=~p,forza=~p, wit=~p, agile=~p where id=~p").
-define(SQL_PET_UPDATE_FORZA, "update pet set forza=~p, aptitude_forza=~p where id=~p").
-define(SQL_PET_UPDATE_WIT, "update pet set wit=~p, aptitude_wit=~p where id=~p").
-define(SQL_PET_UPDATE_AGILE, "update pet set agile=~p, aptitude_agile=~p where id=~p").
-define(SQL_PET_UPDATE_QUALITY, "update pet set quality=~p, aptitude_threshold=~p, level=~p where id=~p").
-define(SQL_PET_UPDATE_STRENGTH_DAILY, "update pet set strength=~p, forza=~p, wit=~p, agile=~p, strength_daily_nexttime=~p where id=~p").
-define(SQL_PET_UPDATE_LOGIN, "update pet set level=~p, upgrade_flag=~p, upgrade_endtime=~p, strength=~p, forza=~p, wit=~p, agile=~p, strength_daily_nexttime=~p where id=~p").
-define(SQL_PET_DELETE, "delete from pet where id = ~p").
-define(SQL_PET_DELETE_ROLE, "delete from pet where player_id = ~p").
-define(SQL_BASE_PET_SELECT_ALL, "select goods_id, goods_name, name, probability from base_pet").
load_base_pet() ->
SQL = io_lib:format(?SQL_BASE_PET_SELECT_ALL, []),
?DEBUG("load_base_pet: SQL=[~s]", [SQL]),
BasePetList = db_sql:get_all(SQL),
lists:map(fun load_base_pet_into_ets/1, BasePetList),
?DEBUG("load_base_pet: [~p] base_pet loaded", [length(BasePetList)]).
load_base_pet_into_ets([GoodsId,GoodsName,Name,Probability]) ->
BasePet = #ets_base_pet{
goods_id = GoodsId,
goods_name = GoodsName,
name = Name,
probability = Probability},
update_base_pet(BasePet).
role_login(PlayerId) ->
?DEBUG("role_login: Loading pets...", []),
PetNum = load_all_pet(PlayerId),
FightingPet = get_fighting_pet(PlayerId),
?DEBUG("role_login: All pet num=[~p], fighting pet num=[~p]", [PetNum, length(FightingPet)]),
计算出战宠物的属性和
calc_pet_attribute_sum(FightingPet).
calc_pet_attribute_sum(Pets) ->
calc_pet_attribute_sum_helper(Pets, 0, 0, 0).
calc_pet_attribute_sum_helper([], TotalForza, TotalWit, TotalAgile) ->
[TotalForza, TotalWit, TotalAgile];
calc_pet_attribute_sum_helper(Pets, TotalForza, TotalWit, TotalAgile) ->
[Pet|PetLeft] = Pets,
calc_pet_attribute_sum_helper(PetLeft, TotalForza+Pet#ets_pet.forza_use, TotalWit+Pet#ets_pet.wit_use, TotalAgile+Pet#ets_pet.agile_use).
load_all_pet(PlayerId) ->
Data = [PlayerId],
SQL = io_lib:format(?SQL_PET_SELECT_ALL_PET, Data),
?DEBUG("load_all_pet: SQL=[~s]", [SQL]),
PetList = db_sql:get_all(SQL),
lists:map(fun load_pet_into_ets/1, PetList),
length(PetList).
load_pet_into_ets([Id,PlayerId,TypeId,TypeName,Name,RenameCount,Level,Quality,_Forza,_Wit,_Agile,BaseForza,BaseWit,BaseAgile,BaseForzaNew,BaseWitNew,BaseAgileNew,AptitudeForza,AptitudeWit,AptitudeAgile,AptitudeThreshold,AttributeShuffleCount,Strength,StrengthDailyNextTime,FightFlag,FightIconPos,UpgradeFlag,UpgradeEndTime,CreateTime,StrengthThreshold,StrengthDaily]) ->
1- 计算出战宠物的下次体力值同步时间
NowTime = util:unixtime(),
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
StrengthNextTime = case FightFlag of
0 -> 0;
1 -> NowTime+IntervalSync;
_ -> ?ERR("load_pet_into_ets: Unknow fight flag, flag=[~p]", FightFlag), 0
end,
2- 收取每日体力
[StrengthNew, StrengthDailyNextTimeNew] = calc_strength_daily(NowTime, StrengthDailyNextTime, Strength, StrengthDaily),
3- 升级完成检测
[LevelNew,UpgradeFlagNew,UpgradeEndTimeNew] = case is_upgrade_finish(UpgradeFlag, UpgradeEndTime) of
true -> [Level+1, 0, 0];
false -> [Level, UpgradeFlag,UpgradeEndTime]
end,
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, LevelNew, StrengthNew),
[ForzaNew, WitNew, AgileNew] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
5-
if ((StrengthNew /= Strength) or (LevelNew > Level)) ->
SQLData = [LevelNew,UpgradeFlagNew,UpgradeEndTimeNew,StrengthNew, ForzaNew, WitNew, AgileNew, StrengthDailyNextTimeNew, Id],
SQL = io_lib:format(?SQL_PET_UPDATE_LOGIN, SQLData),
?DEBUG("load_pet_into_ets: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
true ->
void
end,
Pet = #ets_pet{
id = Id,
player_id = PlayerId,
type_id = TypeId,
type_name = TypeName,
name = Name,
rename_count = RenameCount,
level = LevelNew,
quality = Quality,
forza = ForzaNew,
wit = WitNew,
agile = AgileNew,
base_forza = BaseForza,
base_wit = BaseWit,
base_agile = BaseAgile,
base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
aptitude_forza = AptitudeForza,
aptitude_wit = AptitudeWit,
aptitude_agile = AptitudeAgile,
aptitude_threshold = AptitudeThreshold,
attribute_shuffle_count = AttributeShuffleCount,
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew,
fight_flag = FightFlag,
fight_icon_pos = FightIconPos,
upgrade_flag = UpgradeFlagNew,
upgrade_endtime = UpgradeEndTimeNew,
create_time = CreateTime,
strength_threshold = StrengthThreshold,
strength_daily = StrengthDaily,
strength_nexttime = StrengthNextTime,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse},
update_pet(Pet).
role_logout(PlayerId) ->
PetList = get_all_pet(PlayerId),
lists:map(fun save_pet/1, PetList),
删除所有缓存宠物
delete_all_pet(PlayerId).
save_pet(Pet) ->
Data = [Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
db_sql:execute(SQL).
incubate_pet(PlayerId, GoodsType) ->
?DEBUG("incubate_pet: PlayerId=[~p], GoodsTypeId=[~p]", [PlayerId, GoodsType#ets_goods_type.goods_id]),
解析物品类型
TypeId = GoodsType#ets_goods_type.goods_id,
BasePet = get_base_pet(TypeId),
PetName = case BasePet of
[] -> ?ERR("incubate_pet: Not find the base_pet, goods_id=[~p]", [TypeId]),
make_sure_binary("我的宠物");
_ -> BasePet#ets_base_pet.name
end,
PetQuality = GoodsType#ets_goods_type.color,
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [PetQuality]),
DefaultAptitude = data_pet:get_pet_config(default_aptitude, []),
DefaultLevel = data_pet:get_pet_config(default_level, []),
DefaultStrength = data_pet:get_pet_config(default_strenght, []),
StrengthThreshold = data_pet:get_pet_config(strength_threshold, []),
StrengthDaily = data_pet:get_pet_config(strength_daily, []),
[BaseForza,BaseWit,BaseAgile] = generate_base_attribute(),
AptitudeAttributes = [DefaultAptitude,DefaultAptitude,DefaultAptitude],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, DefaultLevel, DefaultStrength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
插入宠物
CreateTime = util:unixtime(),
StrengthDailyNextTime = CreateTime+(?ONE_DAY_SECONDS),
Data = [PlayerId, TypeId, PetName, PetName, DefaultLevel] ++
[PetQuality, Forza, Wit, Agile, BaseForza, BaseWit, BaseAgile] ++
[AptitudeThreshold, DefaultStrength, StrengthDaily, StrengthThreshold, CreateTime, StrengthDailyNextTime],
SQL = io_lib:format(?SQL_PET_INSERT, Data),
?DEBUG("incubate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
获取新孵化的宠物
Data1 = [PlayerId, TypeId, CreateTime],
SQL1 = io_lib:format(?SQL_PET_SELECT_INCUBATE_PET, Data1),
?DEBUG("incubate_pet: SQL=[~s]", [SQL1]),
IncubateInfo = db_sql:get_row(SQL1),
case IncubateInfo of
[] ->
?ERR("incubate_pet: Failed to incubated pet, PlayerId=[~p], TypeId=[~p], CreateTime=[~p]", [PlayerId, TypeId, CreateTime]),
0;
_ ->
load_pet_into_ets(IncubateInfo),
[PetId| _] = IncubateInfo,
Pet = get_pet(PlayerId, PetId),
?DEBUG("incubate_pet: Cache was upate, PetId=[~p]", [Pet#ets_pet.id]),
[ok, PetId, PetName]
end.
free_pet(PetId) ->
?DEBUG("free_pet: PetId=[~p]", [PetId]),
SQL = io_lib:format(?SQL_PET_DELETE, [PetId]),
?DEBUG("free_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
delete_pet(PetId),
ok.
rename_pet(PetId, PetName, PlayerId, RenameMoney) ->
?DEBUG("rename_pet: PetId=[~p], PetName=[~p], PlayerId=[~p], ModifyMoney=[~p]", [PetId, PetName, PlayerId, RenameMoney]),
Data = [PetName, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_RENAME_INFO, Data),
?DEBUG("rename_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
if RenameMoney > 0 ->
Data1 = [RenameMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("rename_pet: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
true ->
void
end,
ok.
宠物出战
fighting_pet(PetId, FightingPet, FightIconPos) ->
?DEBUG("fighting_pet: PetId=[~p], FightingPet=[~p], FightIconPos=[~p]", [PetId, FightingPet, FightIconPos]),
IconPos = case FightIconPos of
0 -> calc_fight_icon_pos(FightingPet);
1 -> 1;
2 -> 2;
3 -> 3;
_ -> ?ERR("fighting_pet: Unknow fight icon pos = [~p]", [FightIconPos]), 0
end,
if ((IconPos >= 1) and (IconPos =< 3)) ->
Data = [1, IconPos, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("fighting_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, IconPos];
true ->
error
end.
calc_fight_icon_pos(FightingPet) ->
IconPosList = data_pet:get_pet_config(fight_icon_pos_list,[]),
FilteredIconPosList = filter_fight_icon_pos(FightingPet, IconPosList),
case length(FilteredIconPosList) of
0 -> 0;
_ -> lists:nth(1, FilteredIconPosList)
end.
filter_fight_icon_pos([], IconPosList) ->
IconPosList;
filter_fight_icon_pos(FightingPet, IconList) ->
[Pet|PetLeft] = FightingPet,
filter_fight_icon_pos(PetLeft, lists:delete(Pet#ets_pet.fight_icon_pos, IconList)).
rest_pet(PetId) ->
?DEBUG("rest_pet: PetId=[~p]", [PetId]),
Data = [0, 0, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("rest_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
shuffle_attribute(PlayerId, PetId, PayType, ShuffleCount, GoodsId, MoneyGoodsNum, MoneyGoodsUseNum) ->
?DEBUG("shuffle_attribute: PlayerId=[~p],PetId=[~p],PayType=[~p],ShuffleCount=[~p],GoodsId=[~p],MoneyGoodsNum=[~p],MoneyGoodsUseNum=[~p]", [PlayerId, PetId, PayType, ShuffleCount, GoodsId, MoneyGoodsNum, MoneyGoodsUseNum]),
[BaseForza, BaseWit, BaseAgile] = generate_base_attribute(ShuffleCount),
Data = [BaseForza, BaseWit, BaseAgile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_SHUTTLE_INFO, Data),
?DEBUG("shuffle_attribute: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
case PayType of
0 ->
Data1 = [MoneyGoodsUseNum, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("shuffle_attribute: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
_ ->
void
end,
[ok, BaseForza, BaseWit, BaseAgile].
洗练属性使用
use_attribute(PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Stength) ->
?DEBUG("use_attribute: PetId=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], Level=[~p], Stength=[~p]", [PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Stength]),
AptitudeAttributes = [AptitudeForza, AptitudeWit, AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, Stength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
?DEBUG("use_attribut: ForzaUse=[~p], WitUse=[~p], AgileUse=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [ForzaUse, WitUse, AgileUse, Forza, Wit, Agile]),
Data = [Forza, Wit, Agile, BaseForza, BaseWit, BaseAgile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_USE_ATTRIBUTE, Data),
?DEBUG("use_attribute: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse].
pet_start_upgrade(PlayerId, PetId, UpgradeEndTime, UpgradeMoney) ->
?DEBUG("pet_start_upgrade: PlayerId=[~p], PetId=[~p], UpgradeEndTime=[~p], UpgradeMoney=[~p]", [PlayerId, PetId, UpgradeEndTime, UpgradeMoney]),
Data = [1, UpgradeEndTime, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("pet_start_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
Data1 = [UpgradeMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_COIN, Data1),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
shorten_upgrade(PlayerId, PetId, UpgradeEndTime, ShortenMoney) ->
?DEBUG("shorten_upgrade: PlayerId=[~p], PetId=[~p], UpgradeEndTime=[~p], ShortenMoney=[~p]", [PlayerId, PetId, UpgradeEndTime, ShortenMoney]),
Data = [1, UpgradeEndTime, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
Data1 = [ShortenMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("shorten_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
检查宠物升级状态
升完级 : [ 2,升级剩余时间 , 新级别,新力量,新智慧,新敏捷 , 新力量(加成用),新智慧(加成用),新敏捷(加成用 ) ]
check_upgrade_state(PlayerId, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) ->
?DEBUG("check_upgrade_state: PlayerId=[~p], PetId=[~p], Level=[~p], Strength=[~p], UpgradeFlag=[~p], UpgradeEndTime=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p],UpgradeMoney=[~p]", [PlayerId, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney]),
case UpgradeFlag of
不在升级
0 ->
[0, 0];
在升级
1->
NowTime = util:unixtime(),
UpgradeInaccuracy = data_pet:get_pet_config(upgrade_inaccuracy, []),
UpgradeLeftTime = abs(UpgradeEndTime-NowTime),
((NowTime >= UpgradeEndTime) or (UpgradeLeftTime < UpgradeInaccuracy)) ->
case pet_finish_upgrade(PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) of
[ok, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] -> [2, 0, NewLevel,NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse];
_ -> error
end;
true ->
[1, UpgradeLeftTime]
end
end.
pet_finish_upgrade(PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney) ->
?DEBUG("pet_finish_upgrade: PlayerId=[~p], PetId=[~p], Level=[~p], Strength=[~p], AptitudeForza=[~p], AptitudeWit=[~p], AptitudeAgile=[~p], BaseForza=[~p], BaseWit=[~p], BaseAgile=[~p], UpgradeMoney=[~p]", [PlayerId, PetId, Level, Strength, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeMoney]),
NewLevel = Level + 1,
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, NewLevel, Strength),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
?DEBUG("pet_finish_upgrade: Level=[~p], NewLevel=[~p], ForzaUse=[~p], WitUse=[~p], AgileUse=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [Level, NewLevel, ForzaUse, WitUse, AgileUse, Forza, Wit, Agile]),
UpgradeFlag = 0,
UpgradeEndTime = 0,
Data = [NewLevel, UpgradeFlag, UpgradeEndTime, Forza, Wit, Agile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_LEVEL, Data),
?DEBUG("pet_finish_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
UpgradeMoney > 0 ->
Data1 = [UpgradeMoney, PlayerId],
SQL1 = io_lib:format(?SQL_PLAYER_UPDATE_DEDUCT_GOLD, Data1),
?DEBUG("pet_finish_upgrade: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1);
true ->
void
end,
[ok, NewLevel, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse].
extent_upgrade_que(PlayerId, NewQueNum, ExtentQueMoney) ->
Data = [ExtentQueMoney, NewQueNum, PlayerId],
SQL = io_lib:format(?SQL_PLAYER_UPDATE_EXTENT_QUE, Data),
?DEBUG("extent_upgrade_que: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
feed_pet(PetId, PetQuality, FoodQuality, GoodsUseNum, Strength, StrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) ->
?DEBUG("feed_pet: PetId=[~p], PetQuality=[~p], FoodQuality=[~p], GoodsUseNum=[~p], Strength=[~p], PetStrengThreshold=[~p]", [PetId, PetQuality, FoodQuality, GoodsUseNum, Strength, StrengThreshold]),
FoodStrength = data_pet:get_food_strength(PetQuality, FoodQuality),
StrengthTotal = Strength+GoodsUseNum*FoodStrength,
StrengthNew = case StrengthTotal >= StrengThreshold of
true -> StrengThreshold;
false -> StrengthTotal
end,
case is_strength_add_change_attribute(Strength, StrengthNew) of
true ->
AptitudeAttributes = [AptitudeForza,AptitudeWit,AptitudeAgile],
BaseAttributes = [BaseForza,BaseWit,BaseAgile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, StrengthNew),
[Forza, Wit, Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
Data = [StrengthNew, Forza, Wit, Agile, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("feed_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
[ok, StrengthNew, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse];
false ->
[ok, StrengthNew]
end.
domesticate_pet(PetId, DomesticateType, Level, Strength, Aptitude, AptitudeThreshold, BaseAttribute) ->
?DEBUG("domesticate_pet: PetId=[~p], DomesticateType=[~p], Level=[~p], Strength=[~p], Aptitude=[~p], AptitudeThreshold=[~p], BaseAttribute=[~p]", [PetId, DomesticateType, Level, Strength, Aptitude, AptitudeThreshold, BaseAttribute]),
AptitudeValid = case Aptitude > AptitudeThreshold of
true -> AptitudeThreshold;
false -> Aptitude
end,
[AttributeUse] = calc_pet_attribute([AptitudeValid], [BaseAttribute], Level, Strength),
[Attribute] = calc_pet_client_attribute([AttributeUse]),
case DomesticateType of
0 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FORZA, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
1 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_WIT, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
2 ->
Data = [Attribute, AptitudeValid, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_AGILE, Data),
?DEBUG("domesticate_pet: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end,
[ok, AptitudeValid, Attribute, AttributeUse].
宠物进阶
enhance_quality(PetId, Quality, SuccessProbability) ->
?DEBUG("enhance_quality: PetId=[~p], Quality=[~p], SuccessProbability=[~p]", [PetId, Quality, SuccessProbability]),
case get_enhance_quality_result(SuccessProbability) of
true ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [Quality+1]),
Data1 = [Quality+1, AptitudeThreshold, 1, PetId],
SQL1 = io_lib:format(?SQL_PET_UPDATE_QUALITY, Data1),
?DEBUG("enhance_quality: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
[ok, 1, Quality+1, AptitudeThreshold];
false ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold, [Quality]),
[ok, 0, Quality, AptitudeThreshold]
end.
strength_sync([], _NowTime, RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile) ->
[RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile];
strength_sync(Pets, NowTime, RecordsNum, RecordsData, TotalForza, TotalWit, TotalAgile) ->
[Pet|PetLeft] = Pets,
NowTime >= Pet#ets_pet.strength_nexttime ->
[IntervalSync, StrengthSync] = data_pet:get_pet_config(strength_sync, []),
StrengthNew = case Pet#ets_pet.strength > StrengthSync of
true -> Pet#ets_pet.strength-StrengthSync;
false -> 0
end,
?DEBUG("strength_sync: Time arrive, PlayeId=[~p], PetId=[~p], Strength=[~p], StrengthNew=[~p]", [Pet#ets_pet.player_id, Pet#ets_pet.id,Pet#ets_pet.strength, StrengthNew]),
PetId = Pet#ets_pet.id,
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
PetNew = Pet#ets_pet{
strength_nexttime = NowTime+IntervalSync,
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew},
update_pet(PetNew),
SQLData = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, SQLData),
?DEBUG("strength_sync: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
Data = <<PetId:32,StrengthNew:16,1:16, Forza:16, Wit:16, Agile:16>>,
strength_sync(PetLeft, NowTime, RecordsNum+1, list_to_binary([RecordsData, Data]), TotalForza+ForzaUse, TotalWit+WitUse, TotalAgile+AgileUse);
false ->
PetNew = Pet#ets_pet{
strength_nexttime = NowTime+IntervalSync,
strength = StrengthNew},
update_pet(PetNew),
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
ForzaUse = Pet#ets_pet.forza_use,
WitUse = Pet#ets_pet.wit_use,
AgileUse = Pet#ets_pet.agile_use,
Data = <<PetId:32,StrengthNew:16,0:16, Forza:16, Wit:16, Agile:16>>,
strength_sync(PetLeft, NowTime, RecordsNum+1, list_to_binary([RecordsData, Data]), TotalForza+ForzaUse, TotalWit+WitUse, TotalAgile+AgileUse)
end;
true ->
?DEBUG("strength_sync: Not this time, PlayeId=[~p], PetId=[~p], Strength=[~p]", [Pet#ets_pet.player_id, Pet#ets_pet.id,Pet#ets_pet.strength]),
strength_sync(PetLeft, NowTime, RecordsNum, RecordsData, TotalForza+Pet#ets_pet.forza_use, TotalWit+Pet#ets_pet.wit_use, TotalAgile+Pet#ets_pet.agile_use)
end.
get_pet_info(PetId) ->
?DEBUG("get_pet_info: PetId=[~p]", [PetId]),
Pet = get_pet(PetId),
宠物不存在
Pet =:= [] ->
[1, <<>>];
true ->
PetBin = parse_pet_info(Pet),
[1, PetBin]
end.
parse_pet_info(Pet) ->
[Id,Name,RenameCount,Level,Strength,Quality,Forza,Wit,Agile,BaseForza,BaseWit,BaseAgile,BaseForzaNew,BaseWitNew,BaseAgileNew,AptitudeForza,AptitudeWit,AptitudeAgile,AptitudeThreshold,Strength,FightFlag,UpgradeFlag,UpgradeEndtime,FightIconPos, StrengthThreshold, TypeId] =
[Pet#ets_pet.id, Pet#ets_pet.name, Pet#ets_pet.rename_count, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.base_forza_new, Pet#ets_pet.base_wit_new, Pet#ets_pet.base_agile_new, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.aptitude_threshold, Pet#ets_pet.strength, Pet#ets_pet.fight_flag, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime, Pet#ets_pet.fight_icon_pos, Pet#ets_pet.strength_threshold, Pet#ets_pet.type_id],
NameLen = byte_size(Name),
NowTime = util:unixtime(),
UpgradeLeftTime = case UpgradeFlag of
0 -> 0;
1 -> UpgradeEndtime - NowTime;
_ -> ?ERR("parse_pet_info: Unknow upgrade flag = [~p]", [UpgradeFlag])
end,
<<Id:32,NameLen:16,Name/binary,RenameCount:16,Level:16,Quality:16,Forza:16,Wit:16,Agile:16,BaseForza:16,BaseWit:16,BaseAgile:16,BaseForzaNew:16,BaseWitNew:16,BaseAgileNew:16,AptitudeForza:16,AptitudeWit:16,AptitudeAgile:16,AptitudeThreshold:16,Strength:16,FightFlag:16,UpgradeFlag:16,UpgradeLeftTime:32,FightIconPos:16,StrengthThreshold:16, TypeId:32>>.
get_pet_list(PlayerId) ->
PetList = get_all_pet(PlayerId),
RecordNum = length(PetList),
RecordNum == 0 ->
[1, RecordNum, <<>>];
true ->
Records = lists:map(fun parse_pet_info/1, PetList),
[1, RecordNum, list_to_binary(Records)]
end.
fighting_replace(PetId, ReplacedPetId, IconPos) ->
?DEBUG("fighting_replace: PetId=[~p], ReplacedPetId=[~p], IconPos=[~p]", [PetId, ReplacedPetId, IconPos]),
Data = [1, IconPos, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data),
?DEBUG("fighting_replace: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
Data1 = [0, 0, ReplacedPetId],
SQL1 = io_lib:format(?SQL_PET_UPDATE_FIGHT_FLAG, Data1),
?DEBUG("fighting_replace: SQL=[~s]", [SQL1]),
db_sql:execute(SQL1),
ok.
cancel_upgrade(PetId) ->
?DEBUG("cancel_upgrade: PetId=[~p]", [PetId]),
Data = [0, 0, PetId],
SQL = io_lib:format(?SQL_PET_UPDATE_UPGRADE_INFO, Data),
?DEBUG("cancel_upgrade: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
ok.
handle_role_dead(Status) ->
FightingPet = lib_pet:get_fighting_pet(Status#player_status.id),
lists:map(fun handle_pet_dead/1, FightingPet),
if length(FightingPet) > 0 ->
{ok, Bin} = pt_41:write(41000, [0]),
lib_send:send_one(Status#player_status.socket, Bin);
true ->
void
end.
handle_pet_dead(Pet) ->
计算扣取的体力值
DeadStrength = data_pet:get_pet_config(role_dead_strength, []),
StrengthNew = case Pet#ets_pet.strength > DeadStrength of
true -> (Pet#ets_pet.strength - DeadStrength);
false -> 0
end,
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
PetNew = Pet#ets_pet{
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew},
update_pet(PetNew),
Data = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("handle_pet_dead: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
false ->
PetNew = Pet#ets_pet{strength = StrengthNew},
update_pet(PetNew),
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
Data = [StrengthNew, Forza, Wit, Agile, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH, Data),
?DEBUG("handle_pet_dead: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end.
处理每日体力
handle_daily_strength() ->
send_to_all('pet_strength_daily', []),
ok.
collect_strength_daily(Pet) ->
判断是否应该收取
NowTime = util:unixtime(),
[StrengthNew, StrengthDailyNextTimeNew] = calc_strength_daily(NowTime, Pet#ets_pet.strength_daily_nexttime, Pet#ets_pet.strength, Pet#ets_pet.strength_daily),
if StrengthNew /= Pet#ets_pet.strength ->
case is_strength_deduct_change_attribute(Pet#ets_pet.strength, StrengthNew) of
true ->
AptitudeAttributes = [Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit,Pet#ets_pet.aptitude_agile],
BaseAttributes = [Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
[ForzaUse, WitUse, AgileUse] = calc_pet_attribute(AptitudeAttributes, BaseAttributes, Pet#ets_pet.level, StrengthNew),
[Forza,Wit,Agile] = calc_pet_client_attribute([ForzaUse, WitUse, AgileUse]),
PetNew = Pet#ets_pet{
forza = Forza,
wit = Wit,
agile = Agile,
forza_use = ForzaUse,
wit_use = WitUse,
agile_use = AgileUse,
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew},
update_pet(PetNew),
Data = [StrengthNew, Forza, Wit, Agile, StrengthDailyNextTimeNew, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH_DAILY, Data),
?DEBUG("collect_strength_daily: SQL=[~s]", [SQL]),
db_sql:execute(SQL);
false ->
PetNew = Pet#ets_pet{
strength = StrengthNew,
strength_daily_nexttime = StrengthDailyNextTimeNew},
update_pet(PetNew),
Forza = Pet#ets_pet.forza,
Wit = Pet#ets_pet.wit,
Agile = Pet#ets_pet.agile,
Data = [StrengthNew, Forza, Wit, Agile, StrengthDailyNextTimeNew, Pet#ets_pet.id],
SQL = io_lib:format(?SQL_PET_UPDATE_STRENGTH_DAILY, Data),
?DEBUG("collect_strength_daily: SQL=[~s]", [SQL]),
db_sql:execute(SQL)
end;
true ->
void
end.
delete_role(PlayerId) ->
?DEBUG("delete_role: PlayerId=[~p]", [PlayerId]),
Data = [PlayerId],
SQL = io_lib:format(?SQL_PET_DELETE_ROLE, Data),
?DEBUG("delete_role: SQL=[~s]", [SQL]),
db_sql:execute(SQL),
delete_all_pet(PlayerId),
ok.
make_sure_binary(String) ->
case is_binary(String) of
true -> String;
false when is_list(String) -> list_to_binary(String);
false ->
?ERR("make_sure_binary: Error string=[~w]", [String]),
String
end.
send_to_all(MsgType, Bin) ->
Pids = ets:match(?ETS_ONLINE, #ets_online{pid='$1', _='_'}),
F = fun([P]) ->
gen_server:cast(P, {MsgType, Bin})
end,
[F(Pid) || Pid <- Pids].
seconds_to_localtime(Seconds) ->
DateTime = calendar:gregorian_seconds_to_datetime(Seconds+?DIFF_SECONDS_0000_1900),
calendar:universal_time_to_local_time(DateTime).
判断是否同一天
is_same_date(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, _Time1} = seconds_to_localtime(Seconds1),
{{Year2, Month2, Day2}, _Time2} = seconds_to_localtime(Seconds2),
if ((Year1 /= Year2) or (Month1 /= Month2) or (Day1 /= Day2)) -> false;
true -> true
end.
is_same_week(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, Time1} = seconds_to_localtime(Seconds1),
星期几
Week1 = calendar:day_of_the_week(Year1, Month1, Day1),
Diff1 = calendar:time_to_seconds(Time1),
Monday = Seconds1 - Diff1 - (Week1-1)*?ONE_DAY_SECONDS,
Sunday = Seconds1 + (?ONE_DAY_SECONDS-Diff1) + (7-Week1)*?ONE_DAY_SECONDS,
if ((Seconds2 >= Monday) and (Seconds2 < Sunday)) -> true;
true -> false
end.
get_midnight_seconds(Seconds) ->
{{_Year, _Month, _Day}, Time} = seconds_to_localtime(Seconds),
Diff = calendar:time_to_seconds(Time),
Today = Seconds - Diff,
NextDay = Seconds + (?ONE_DAY_SECONDS-Diff),
{Today, NextDay}.
get_diff_days(Seconds1, Seconds2) ->
{{Year1, Month1, Day1}, _} = seconds_to_localtime(Seconds1),
{{Year2, Month2, Day2}, _} = seconds_to_localtime(Seconds2),
Days1 = calendar:date_to_gregorian_days(Year1, Month1, Day1),
Days2 = calendar:date_to_gregorian_days(Year2, Month2, Day2),
DiffDays=abs(Days2-Days1),
DiffDays+1.
generate_base_attribute() ->
BaseAttributeSum = data_pet:get_pet_config(base_attribute_sum, []),
BaseForza = util:rand(1, BaseAttributeSum - 2),
BaseWit = util:rand(1, BaseAttributeSum - BaseForza - 1),
BaseAgile = BaseAttributeSum - BaseForza - BaseWit,
[BaseForza, BaseWit, BaseAgile].
generate_base_attribute(ShuffleCount) ->
LuckyShuffleCount = data_pet:get_pet_config(lucky_shuffle_count, []),
if ShuffleCount >= LuckyShuffleCount ->
generate_base_attribute_lucky();
true ->
generate_base_attribute()
end.
generate_base_attribute_lucky() ->
BaseAttributeSum = data_pet:get_pet_config(base_attribute_sum, []),
LuckyBaseAttribute = data_pet:get_pet_config(lucky_base_attribute, []),
LeftAttribute = BaseAttributeSum-LuckyBaseAttribute,
BaseForza = util:rand(1, LeftAttribute-2),
BaseWit = util:rand(1, LeftAttribute-BaseForza-1),
BaseAgile = LeftAttribute-BaseForza-BaseWit,
Index = util:rand(1, 3),
if Index == 1 ->
[BaseForza+LuckyBaseAttribute,BaseWit,BaseAgile];
Index == 2 ->
[BaseForza,BaseWit+LuckyBaseAttribute,BaseAgile];
Index == 3 ->
[BaseForza,BaseWit,BaseAgile+LuckyBaseAttribute]
end.
calc_pet_attribute(AptitudeAttributes, BaseAttributes, Level, Strength) ->
calc_pet_attribute_helper(AptitudeAttributes, BaseAttributes, Level, Strength, []).
calc_pet_attribute_helper([], [], _Level, _Strength, Attributes) ->
Attributes;
calc_pet_attribute_helper(AptitudeAttributes, BaseAttributes, Level, Strength, Attributes) ->
[AptitudeAttribute|AptitudeAttributeLeft] = AptitudeAttributes,
[BaseAttribute|BaseAttributeLeft] = BaseAttributes,
0.1+(当前资质/100+基础值)*(当前等级-1)*0.0049
Attribute = 0.1 + (AptitudeAttribute/100+BaseAttribute)*(Level-1)*0.0049,
if Strength =< 0 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[0]);
Strength =< 50 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute*0.5]);
Strength =< 90 ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute]);
true ->
calc_pet_attribute_helper(AptitudeAttributeLeft, BaseAttributeLeft, Level, Strength, Attributes++[Attribute*1.2])
end.
calc_pet_client_attribute(Attributes)->
calc_pet_client_attribute_helper(Attributes, []).
calc_pet_client_attribute_helper([], ClientAttributes) ->
ClientAttributes;
calc_pet_client_attribute_helper(Attributes, ClientAttributes) ->
[Attribute|AttributeLeft] = Attributes,
NewAttribute = round(Attribute*10),
calc_pet_client_attribute_helper(AttributeLeft, ClientAttributes++[NewAttribute]).
计算宠物属性加点到角色的影响
calc_player_attribute(Type, Status, Forza, Wit, Agile) ->
?DEBUG("calc_player_attribute:Type=[~p], Forza=[~p], Wit=[~p], Agile=[~p]", [Type, Forza, Wit, Agile]),
[NewPetForza, NewPetWit, NewPetAgile] = case Type of
add ->
[PetForza, PetWit, PetAgile] = Status#player_status.pet_attribute,
[PetForza+Forza, PetWit+Wit, PetAgile+Agile];
deduct ->
[PetForza, PetWit, PetAgile] = Status#player_status.pet_attribute,
[PetForza-Forza, PetWit-Wit, PetAgile-Agile];
replace -> [Forza, Wit, Agile]
end,
Status1 = Status#player_status{pet_attribute = [NewPetForza,NewPetWit,NewPetAgile]},
Status2 = lib_player:count_player_attribute(Status1),
if Status1#player_status.hp_lim =/= Status2#player_status.hp_lim ->
{ok, SceneData} = pt_12:write(12009, [Status#player_status.id, Status2#player_status.hp, Status2#player_status.hp_lim]),
lib_send:send_to_area_scene(Status2#player_status.scene, Status2#player_status.x, Status2#player_status.y, SceneData);
true ->
void
end,
lib_player:send_attribute_change_notify(Status2, 1),
Status2.
calc_new_hp_mp(HpMp, HpMpLimit, HpMpLimitNew) ->
case HpMpLimit =/= HpMpLimitNew of
true ->
case HpMp > HpMpLimitNew of
true -> HpMpLimitNew;
false -> HpMp
end;
false ->
HpMp
end.
计算升级加速所需金币
calc_shorten_money(ShortenTime) ->
[MoneyUnit, Unit] = data_pet:get_pet_config(shorten_money_unit,[]),
TotalUnit = util:ceil(ShortenTime/Unit),
MoneyUnit * TotalUnit.
calc_strength_daily(NowTime, StrengthDailyNextTime, Strength, StrengthDaily) ->
{_Today, NextDay} = get_midnight_seconds(NowTime),
StrengthDailyNextTime =< NextDay ->
DiffDays = get_diff_days(StrengthDailyNextTime, NowTime),
StrengthTotal = StrengthDaily*DiffDays,
StrengthNew = case Strength > StrengthTotal of
true -> Strength - StrengthTotal;
false -> 0
end,
StrengthDailyNextTimeNew = NowTime+(?ONE_DAY_SECONDS),
[StrengthNew, StrengthDailyNextTimeNew];
true ->
[Strength, StrengthDailyNextTime]
end.
is_upgrade_finish(UpgradeFlag, UpgradeEndTime) ->
case UpgradeFlag of
不在升级
0 ->
false;
在升级
1->
NowTime = util:unixtime(),
UpgradeInaccuracy = data_pet:get_pet_config(upgrade_inaccuracy, []),
UpgradeLeftTime = abs(UpgradeEndTime-NowTime),
((NowTime >= UpgradeEndTime) or (UpgradeLeftTime < UpgradeInaccuracy)) -> true;
true -> false
end
end.
is_strength_deduct_change_attribute(Strength, StrengthNew) ->
if ((StrengthNew == 0) and (Strength > 0)) -> true;
((StrengthNew =< 50) and (Strength > 50)) -> true;
((StrengthNew =< 90) and (Strength > 90)) -> true;
true -> false
end.
判断体力值增加是否改变角色属性
is_strength_add_change_attribute(Strength, StrengthNew) ->
if ((Strength =< 90) and (StrengthNew > 90)) -> true;
((Strength =< 50) and (StrengthNew > 50)) -> true;
((Strength == 0) and (StrengthNew > 0)) -> true;
true -> false
end.
get_enhance_quality_result(SuccessProbability) ->
RandNumer = util:rand(1, 100),
if (RandNumer > SuccessProbability) -> false;
true -> true
end.
缓存操作函数
通用函数
lookup_one(Table, Key) ->
Record = ets:lookup(Table, Key),
if Record =:= [] ->
[];
true ->
[R] = Record,
R
end.
lookup_all(Table, Key) ->
ets:lookup(Table, Key).
match_one(Table, Pattern) ->
Record = ets:match_object(Table, Pattern),
if Record =:= [] ->
[];
true ->
[R] = Record,
R
end.
match_all(Table, Pattern) ->
ets:match_object(Table, Pattern).
get_fighting_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, fight_flag=1, _='_'}).
get_pet(PlayerId, PetId) ->
match_one(?ETS_PET, #ets_pet{id=PetId, player_id=PlayerId, _='_'}).
get_pet(PetId) ->
lookup_one(?ETS_PET, PetId).
get_all_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, _='_'}).
get_pet_count(PlayerId) ->
length(get_all_pet(PlayerId)).
get_upgrading_pet(PlayerId) ->
match_all(?ETS_PET, #ets_pet{player_id=PlayerId, upgrade_flag=1, _='_'}).
update_pet(Pet) ->
ets:insert(?ETS_PET, Pet).
delete_pet(PetId) ->
ets:delete(?ETS_PET, PetId).
delete_all_pet(PlayerId) ->
ets:match_delete(?ETS_PET, #ets_pet{player_id=PlayerId, _='_'}).
get_base_pet(GoodsId) ->
lookup_one(?ETS_BASE_PET, GoodsId).
update_base_pet(BasePet) ->
ets:insert(?ETS_BASE_PET, BasePet).
get_goods(GoodsId) ->
match_one(?ETS_GOODS_ONLINE, #goods{id=GoodsId, location=4, _='_'}).
get_goods_type(GoodsId) ->
lookup_one(?ETS_GOODS_TYPE,GoodsId).
|
e341ef71a6a9334096778a3e1c975948e38ef1e8ec1e2d8e01350155ccd0ed69 | inhabitedtype/ocaml-aws | restoreDBInstanceToPointInTime.mli | open Types
type input = RestoreDBInstanceToPointInTimeMessage.t
type output = RestoreDBInstanceToPointInTimeResult.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/restoreDBInstanceToPointInTime.mli | ocaml | open Types
type input = RestoreDBInstanceToPointInTimeMessage.t
type output = RestoreDBInstanceToPointInTimeResult.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| |
c01eb541df8e0e1393492e631602c9dee3187c096699f7fe50939d3fa2879f8b | diagrams/diagrams-cairo | Explode.hs | # LANGUAGE NoMonomorphismRestriction #
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
u = vrule 1 # reflectY
r = hrule 1
tr = mconcat [u, u, r, u, r, r, r, u]
ps = explodeTrail origin tr
d = strokeT tr
# lc red
# centerXY
d2 = ps
# map assignColor
# map (\(p,c) -> lc c . stroke $ p)
# lw 0.05
# centerXY
# mconcat
assignColor p | direction v < 1/8 = (p,red)
| otherwise = (p,blue)
where [v] = pathOffsets p
main = defaultMain (pad 1.1 d2) | null | https://raw.githubusercontent.com/diagrams/diagrams-cairo/533e4f4f18f961543bb1d78493c750dec45fd4a3/test/Explode.hs | haskell | # LANGUAGE NoMonomorphismRestriction #
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
u = vrule 1 # reflectY
r = hrule 1
tr = mconcat [u, u, r, u, r, r, r, u]
ps = explodeTrail origin tr
d = strokeT tr
# lc red
# centerXY
d2 = ps
# map assignColor
# map (\(p,c) -> lc c . stroke $ p)
# lw 0.05
# centerXY
# mconcat
assignColor p | direction v < 1/8 = (p,red)
| otherwise = (p,blue)
where [v] = pathOffsets p
main = defaultMain (pad 1.1 d2) | |
f17bcbbb2149a7aa22fe71f773ae873ff785021c1c3c06f61f9f6bed94791c3b | froggey/Mezzano | float.lisp | ;;;; Floating point numbers
(in-package :mezzano.internals)
;;; Short-Floats
(defun %integer-as-short-float (value)
(check-type value (unsigned-byte 16))
(let ((result (mezzano.runtime::%allocate-object
sys.int::+object-tag-short-float+ 0 1 nil)))
(setf (%object-ref-unsigned-byte-16 result 0) value)
result))
(defun %short-float-as-integer (value)
(check-type value short-float)
(%object-ref-unsigned-byte-16 value 0))
(defun mezzano.runtime::%%coerce-fixnum-to-short-float (value)
(mezzano.runtime::%%coerce-single-float-to-short-float
(mezzano.runtime::%%coerce-fixnum-to-single-float value)))
;; see
;; float_to_half_fast3_rtne
(defun mezzano.runtime::%%coerce-single-float-to-short-float (value)
(let* ((f32infty (%single-float-as-integer
single-float-positive-infinity))
(f16max (ash (+ 127 16) 23))
(denorm-magicu (ash (+ (- 127 15) (- 23 10) 1) 23))
(denorm-magic (%integer-as-single-float
denorm-magicu))
(sign-mask #x80000000)
(o nil)
(fu (%single-float-as-integer value))
(ff value)
(sign (logand fu sign-mask)))
(setf fu (logxor fu sign)
ff (%integer-as-single-float fu))
(cond ((>= fu f16max)
result is Inf or NaN ( all exponent bits set )
NaN->qNaN and Inf->Inf
#x7E00
#x7C00)))
resulting FP16 is subnormal or zero
use a magic value to align our 10 mantissa bits at the bottom of
the float . as long as FP addition is round - to - nearest - even this
;; just works.
(incf ff denorm-magic)
(setf fu (%single-float-as-integer ff))
and one integer subtract of the bias later , we have our final float !
(setf o (- fu denorm-magicu)))
(t
(let ((mant-odd (logand (ash fu 13) 1))) ; resulting mantissa is odd
update exponent , rounding bias part 1
(incf fu (+ (ash (- 15 127) 23) #xfff))
rounding bias part 2
(incf fu mant-odd)
;; take the bits!
(setf o (ash fu -13)))))
(%integer-as-short-float (logior (ash sign -16) o))))
;; half_to_float
(defun mezzano.runtime::%%coerce-short-float-to-single-float (value)
(let* ((magic (%integer-as-single-float (ash 113 23)))
(shifted-exp (ash #x7C00 13)) ; exponent mask after shift
(hu (%short-float-as-integer value))
(o nil))
(setf o (ash (logand hu #x7FFF) 13)) ; exponent/mantissa bits
(let ((exp (logand shifted-exp o))) ; just the exponent
(incf o (ash (- 127 15) 23)) ; exponent adjust
;; handle exponent special cases
Inf / NaN ?
(incf o (ash (- 128 16) 23))) ; extra exp adjust
((eql exp 0) ; Zero/Denormal?
(incf o (ash 1 23)) ; extra exp adjust
(let ((of (%integer-as-single-float o)))
(decf of magic) ; renormalize
(setf o (%single-float-as-integer of)))))
(setf o (logior o (ash (logand hu #x8000) 16))) ; sign bit
(%integer-as-single-float o))))
(defun mezzano.runtime::%%coerce-double-float-to-short-float (value)
(mezzano.runtime::%%coerce-single-float-to-short-float
(mezzano.runtime::%%coerce-double-float-to-single-float value)))
(defun mezzano.runtime::%%coerce-short-float-to-double-float (value)
(mezzano.runtime::%%coerce-single-float-to-double-float
(mezzano.runtime::%%coerce-short-float-to-single-float value)))
(macrolet ((def (name op)
`(defun ,name (x y)
(float (,op (float x 0.0f0)
(float y 0.0f0))
0.0s0)))
(def-pred (name op)
`(defun ,name (x y)
(,op (float x 0.0f0)
(float y 0.0f0)))))
(def-pred %%short-float-< <)
(def-pred %%short-float-= =)
(def %%short-float-+ +)
(def %%short-float-- -)
(def %%short-float-* *)
(def %%short-float-/ /))
(defun %%truncate-short-float (val)
(multiple-value-bind (quot rem)
(truncate (float val 0.0f0))
(values quot (float rem 0.0s0))))
(defun %%short-float-sqrt (value)
(float (sqrt (float value 0.0f0)) 0.0s0))
| null | https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/system/numbers/float.lisp | lisp | Floating point numbers
Short-Floats
see
float_to_half_fast3_rtne
just works.
resulting mantissa is odd
take the bits!
half_to_float
exponent mask after shift
exponent/mantissa bits
just the exponent
exponent adjust
handle exponent special cases
extra exp adjust
Zero/Denormal?
extra exp adjust
renormalize
sign bit |
(in-package :mezzano.internals)
(defun %integer-as-short-float (value)
(check-type value (unsigned-byte 16))
(let ((result (mezzano.runtime::%allocate-object
sys.int::+object-tag-short-float+ 0 1 nil)))
(setf (%object-ref-unsigned-byte-16 result 0) value)
result))
(defun %short-float-as-integer (value)
(check-type value short-float)
(%object-ref-unsigned-byte-16 value 0))
(defun mezzano.runtime::%%coerce-fixnum-to-short-float (value)
(mezzano.runtime::%%coerce-single-float-to-short-float
(mezzano.runtime::%%coerce-fixnum-to-single-float value)))
(defun mezzano.runtime::%%coerce-single-float-to-short-float (value)
(let* ((f32infty (%single-float-as-integer
single-float-positive-infinity))
(f16max (ash (+ 127 16) 23))
(denorm-magicu (ash (+ (- 127 15) (- 23 10) 1) 23))
(denorm-magic (%integer-as-single-float
denorm-magicu))
(sign-mask #x80000000)
(o nil)
(fu (%single-float-as-integer value))
(ff value)
(sign (logand fu sign-mask)))
(setf fu (logxor fu sign)
ff (%integer-as-single-float fu))
(cond ((>= fu f16max)
result is Inf or NaN ( all exponent bits set )
NaN->qNaN and Inf->Inf
#x7E00
#x7C00)))
resulting FP16 is subnormal or zero
use a magic value to align our 10 mantissa bits at the bottom of
the float . as long as FP addition is round - to - nearest - even this
(incf ff denorm-magic)
(setf fu (%single-float-as-integer ff))
and one integer subtract of the bias later , we have our final float !
(setf o (- fu denorm-magicu)))
(t
update exponent , rounding bias part 1
(incf fu (+ (ash (- 15 127) 23) #xfff))
rounding bias part 2
(incf fu mant-odd)
(setf o (ash fu -13)))))
(%integer-as-short-float (logior (ash sign -16) o))))
(defun mezzano.runtime::%%coerce-short-float-to-single-float (value)
(let* ((magic (%integer-as-single-float (ash 113 23)))
(hu (%short-float-as-integer value))
(o nil))
Inf / NaN ?
(let ((of (%integer-as-single-float o)))
(setf o (%single-float-as-integer of)))))
(%integer-as-single-float o))))
(defun mezzano.runtime::%%coerce-double-float-to-short-float (value)
(mezzano.runtime::%%coerce-single-float-to-short-float
(mezzano.runtime::%%coerce-double-float-to-single-float value)))
(defun mezzano.runtime::%%coerce-short-float-to-double-float (value)
(mezzano.runtime::%%coerce-single-float-to-double-float
(mezzano.runtime::%%coerce-short-float-to-single-float value)))
(macrolet ((def (name op)
`(defun ,name (x y)
(float (,op (float x 0.0f0)
(float y 0.0f0))
0.0s0)))
(def-pred (name op)
`(defun ,name (x y)
(,op (float x 0.0f0)
(float y 0.0f0)))))
(def-pred %%short-float-< <)
(def-pred %%short-float-= =)
(def %%short-float-+ +)
(def %%short-float-- -)
(def %%short-float-* *)
(def %%short-float-/ /))
(defun %%truncate-short-float (val)
(multiple-value-bind (quot rem)
(truncate (float val 0.0f0))
(values quot (float rem 0.0s0))))
(defun %%short-float-sqrt (value)
(float (sqrt (float value 0.0f0)) 0.0s0))
|
3a12da9e817bc8d00eb99c85ad97f02d2636a5d3f9dbf6bb8be679285f0d967c | futurice/haskell-mega-repo | HoursMock.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Futurice.App.HoursMock (defaultMain) where
import Futurice.Prelude
import Futurice.Servant
import Prelude ()
import Servant
import Futurice.App.HoursApi.API
import Futurice.App.HoursApi.Logic
import Futurice.App.HoursMock.Config (Config (..))
import Futurice.App.HoursMock.Ctx
import Futurice.App.HoursMock.Monad
server :: Ctx -> Server FutuhoursAPI
server ctx = pure "This is futuhours mock api"
:<|> v1Server ctx
:<|> pure []
v1Server :: Ctx -> Server FutuhoursV1API
v1Server ctx =
(\_ -> runHours ctx projectEndpoint)
:<|> (\_ -> runHours ctx userEndpoint)
:<|> (\_ a b -> runHours ctx (hoursEndpoint a b))
:<|> (\_ eu -> runHours ctx (entryEndpoint eu))
:<|> (\_ eid eu -> runHours ctx (entryEditEndpoint eid eu))
:<|> (\_ eid -> runHours ctx (entryDeleteEndpoint eid))
:<|> (\_ eids -> runHours ctx (entryDeleteMultipleEndpoint eids))
defaultMain :: IO ()
defaultMain = futuriceServerMain (const makeCtx) $ emptyServerConfig
& serverService .~ HoursApiService -- same as in real!
& serverDescription .~ "Is it real?"
& serverApp futuhoursApi .~ server
& serverColour .~ (Proxy :: Proxy ('FutuAccent 'AF4 'AC1))
& serverEnvPfx .~ "FUTUHOURSMOCK"
where
makeCtx :: Config -> Logger -> Manager -> Cache -> MessageQueue -> IO (Ctx, [Job])
makeCtx _ _ _ _ _ = do
ctx <- newCtx
pure (ctx, [])
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/hours-api/src/Futurice/App/HoursMock.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
same as in real! | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Futurice.App.HoursMock (defaultMain) where
import Futurice.Prelude
import Futurice.Servant
import Prelude ()
import Servant
import Futurice.App.HoursApi.API
import Futurice.App.HoursApi.Logic
import Futurice.App.HoursMock.Config (Config (..))
import Futurice.App.HoursMock.Ctx
import Futurice.App.HoursMock.Monad
server :: Ctx -> Server FutuhoursAPI
server ctx = pure "This is futuhours mock api"
:<|> v1Server ctx
:<|> pure []
v1Server :: Ctx -> Server FutuhoursV1API
v1Server ctx =
(\_ -> runHours ctx projectEndpoint)
:<|> (\_ -> runHours ctx userEndpoint)
:<|> (\_ a b -> runHours ctx (hoursEndpoint a b))
:<|> (\_ eu -> runHours ctx (entryEndpoint eu))
:<|> (\_ eid eu -> runHours ctx (entryEditEndpoint eid eu))
:<|> (\_ eid -> runHours ctx (entryDeleteEndpoint eid))
:<|> (\_ eids -> runHours ctx (entryDeleteMultipleEndpoint eids))
defaultMain :: IO ()
defaultMain = futuriceServerMain (const makeCtx) $ emptyServerConfig
& serverDescription .~ "Is it real?"
& serverApp futuhoursApi .~ server
& serverColour .~ (Proxy :: Proxy ('FutuAccent 'AF4 'AC1))
& serverEnvPfx .~ "FUTUHOURSMOCK"
where
makeCtx :: Config -> Logger -> Manager -> Cache -> MessageQueue -> IO (Ctx, [Job])
makeCtx _ _ _ _ _ = do
ctx <- newCtx
pure (ctx, [])
|
3d682c96d130a0d4d2d449f8faef591d3493956d24dac1f5dbeb27a500840f6e | d-plaindoux/transept | transept_stream.mli | (** The [Transept_streams] provides an implementation on top of elements list
and on top of a parser. In addition [Iterator] can be derived from these
streams. *)
module Via_list = List.Via_list
(** Define stream construction from elements list source. *)
module Via_parser = Parser.Make
(** Define stream construction from parser. *)
module Iterator = Iterator.Make
(** Define iterator generator/ *)
| null | https://raw.githubusercontent.com/d-plaindoux/transept/8567803721f6c3f5d876131b15cb301cb5b084a4/lib/transept_stream/transept_stream.mli | ocaml | * The [Transept_streams] provides an implementation on top of elements list
and on top of a parser. In addition [Iterator] can be derived from these
streams.
* Define stream construction from elements list source.
* Define stream construction from parser.
* Define iterator generator/ |
module Via_list = List.Via_list
module Via_parser = Parser.Make
module Iterator = Iterator.Make
|
61a2c5025d573689a2c99ef91d11ccc86241c7adbb0c8d6913625935c4a32f71 | sjl/cl-nrepl | evaluation.lisp | (in-package :nrepl)
(defvar *last-trace* nil)
(define-condition evaluation-error (error)
((text :initarg :text :reader text)
(orig :initarg :orig :reader orig)
(data :initarg :data :reader data :initform ())))
(defclass evaluator ()
((standard-input :initarg :in :reader in)
(standard-output :initarg :out :reader out)
(standard-error :initarg :err :reader err)))
(defun read-data (stream)
(flex:octets-to-string
(flex:get-output-stream-sequence stream)
:external-format :utf-8))
(defun shuttle-stream (stream stream-name message)
"Read data from `stream` and shuttle it back to the client.
Chunks of data will be read from `stream` until it's finished and closed.
For each hunk of data read, a response will be sent back to the client using
the transport defined in `message`, looking something like:
{\"status\" \"ok\"
\"stdout\" \"...data...\"}
`stream-name` should be the name of the stream being shuttled, like
\"stderr\", and will be used as the key in the response.
"
(loop
:for data = (read-data stream)
:until (and (not (open-stream-p stream))
(equal data ""))
:do (progn
(when (not (string= data ""))
(respond message (make-map "status" '("ok")
stream-name data)))
(sleep 0.1))))
(defun get-forms (code)
"Get all lisp forms from `code`.
If `code` is a string, the forms will be read out of it, and an
`evaluation-error` signaled if the input is mangled.
If `code` is anything else it will just be returned as-is.
"
(if (stringp code)
(handler-case
(read-all-from-string code)
(error (e)
(error 'evaluation-error
:text "Malformed input!"
:orig e)))
code))
(defun parse-frame (frame)
(let ((call-form (list* (dissect:call frame) (dissect:args frame)))
(location (list (dissect:file frame) (dissect:line frame))))
(list call-form location)))
(defun parse-stack (stack)
(mapcar #'parse-frame (nthcdr 1 (reverse stack))))
(defun string-trace-whole (trace)
(with-output-to-string (s)
(loop :for (call-form (file line)) :in trace
:do (format s "~S~%" call-form))))
(defun string-trace-components (trace)
(loop :for (call-form (file line)) :in trace
:collect (list (format nil "~S" call-form)
(if file
(format nil "~A" file)
"")
(if line
(format nil "~D" line)
""))))
(defun nrepl-evaluate-form (form)
(declare (optimize (debug 3)))
(prin1-to-string
(handler-bind
((error
(lambda (err)
; if we hit an error, get the stack trace before reraising. if we
wait til later to print it , it 'll be too late .
(error 'evaluation-error
:text "Error during evaluation!"
:orig err
:data (let* ((raw (dissect:stack))
(clean (parse-stack raw)))
(setf *last-trace* raw)
(list
"form" (prin1-to-string form)
"stack-trace" (string-trace-components clean)
"stack-trace-string" (string-trace-whole clean)))))))
(dissect:with-truncated-stack ()
(eval form)))))
(defun evaluate-forms (message forms &optional in-package)
"Evaluate each form in `forms` and shuttle back the responses.
`forms` can be a string, in which case the forms will be read out of it, or
a ready-to-go list of actual forms.
`in-package` can be a package designator, or `nil` to just use `*package*`.
"
(let* ((captured-out (flex:make-in-memory-output-stream))
(captured-err (flex:make-in-memory-output-stream))
(*standard-output*
(flex:make-flexi-stream captured-out :external-format :utf-8))
(*error-output*
(flex:make-flexi-stream captured-err :external-format :utf-8)))
(flet ((eval-form (form)
(let ((result (nrepl-evaluate-form form)))
(respond message
(make-map "form" (prin1-to-string form)
"value" result))))
(error-respond (e)
(respond message
(apply #'make-map
"status" '("error")
"error" (text e)
"original" (format nil "~S" (orig e))
(data e))))
(make-shuttle-thread (stream desc)
(bt:make-thread
(lambda () (shuttle-stream stream desc message))
:name (format nil "NREPL ~A writer" desc))))
(unwind-protect
(progn
(make-shuttle-thread captured-out "stdout")
(make-shuttle-thread captured-err "stderr")
(handler-case
(progn
(let ((*package* (parse-in-package in-package)))
(mapc #'eval-form (get-forms forms)))
(respond message (make-map "status" '("done"))))
(evaluation-error (e) (error-respond e))))
(close captured-out)
(close captured-err)))))
| null | https://raw.githubusercontent.com/sjl/cl-nrepl/20a71458344a721d605c349b92268879bdfc98a1/src/evaluation.lisp | lisp | if we hit an error, get the stack trace before reraising. if we | (in-package :nrepl)
(defvar *last-trace* nil)
(define-condition evaluation-error (error)
((text :initarg :text :reader text)
(orig :initarg :orig :reader orig)
(data :initarg :data :reader data :initform ())))
(defclass evaluator ()
((standard-input :initarg :in :reader in)
(standard-output :initarg :out :reader out)
(standard-error :initarg :err :reader err)))
(defun read-data (stream)
(flex:octets-to-string
(flex:get-output-stream-sequence stream)
:external-format :utf-8))
(defun shuttle-stream (stream stream-name message)
"Read data from `stream` and shuttle it back to the client.
Chunks of data will be read from `stream` until it's finished and closed.
For each hunk of data read, a response will be sent back to the client using
the transport defined in `message`, looking something like:
{\"status\" \"ok\"
\"stdout\" \"...data...\"}
`stream-name` should be the name of the stream being shuttled, like
\"stderr\", and will be used as the key in the response.
"
(loop
:for data = (read-data stream)
:until (and (not (open-stream-p stream))
(equal data ""))
:do (progn
(when (not (string= data ""))
(respond message (make-map "status" '("ok")
stream-name data)))
(sleep 0.1))))
(defun get-forms (code)
"Get all lisp forms from `code`.
If `code` is a string, the forms will be read out of it, and an
`evaluation-error` signaled if the input is mangled.
If `code` is anything else it will just be returned as-is.
"
(if (stringp code)
(handler-case
(read-all-from-string code)
(error (e)
(error 'evaluation-error
:text "Malformed input!"
:orig e)))
code))
(defun parse-frame (frame)
(let ((call-form (list* (dissect:call frame) (dissect:args frame)))
(location (list (dissect:file frame) (dissect:line frame))))
(list call-form location)))
(defun parse-stack (stack)
(mapcar #'parse-frame (nthcdr 1 (reverse stack))))
(defun string-trace-whole (trace)
(with-output-to-string (s)
(loop :for (call-form (file line)) :in trace
:do (format s "~S~%" call-form))))
(defun string-trace-components (trace)
(loop :for (call-form (file line)) :in trace
:collect (list (format nil "~S" call-form)
(if file
(format nil "~A" file)
"")
(if line
(format nil "~D" line)
""))))
(defun nrepl-evaluate-form (form)
(declare (optimize (debug 3)))
(prin1-to-string
(handler-bind
((error
(lambda (err)
wait til later to print it , it 'll be too late .
(error 'evaluation-error
:text "Error during evaluation!"
:orig err
:data (let* ((raw (dissect:stack))
(clean (parse-stack raw)))
(setf *last-trace* raw)
(list
"form" (prin1-to-string form)
"stack-trace" (string-trace-components clean)
"stack-trace-string" (string-trace-whole clean)))))))
(dissect:with-truncated-stack ()
(eval form)))))
(defun evaluate-forms (message forms &optional in-package)
"Evaluate each form in `forms` and shuttle back the responses.
`forms` can be a string, in which case the forms will be read out of it, or
a ready-to-go list of actual forms.
`in-package` can be a package designator, or `nil` to just use `*package*`.
"
(let* ((captured-out (flex:make-in-memory-output-stream))
(captured-err (flex:make-in-memory-output-stream))
(*standard-output*
(flex:make-flexi-stream captured-out :external-format :utf-8))
(*error-output*
(flex:make-flexi-stream captured-err :external-format :utf-8)))
(flet ((eval-form (form)
(let ((result (nrepl-evaluate-form form)))
(respond message
(make-map "form" (prin1-to-string form)
"value" result))))
(error-respond (e)
(respond message
(apply #'make-map
"status" '("error")
"error" (text e)
"original" (format nil "~S" (orig e))
(data e))))
(make-shuttle-thread (stream desc)
(bt:make-thread
(lambda () (shuttle-stream stream desc message))
:name (format nil "NREPL ~A writer" desc))))
(unwind-protect
(progn
(make-shuttle-thread captured-out "stdout")
(make-shuttle-thread captured-err "stderr")
(handler-case
(progn
(let ((*package* (parse-in-package in-package)))
(mapc #'eval-form (get-forms forms)))
(respond message (make-map "status" '("done"))))
(evaluation-error (e) (error-respond e))))
(close captured-out)
(close captured-err)))))
|
94db01618ce6e46be05d6f31b08622aef8cde9909f4d74cb8e24b6d8507d32db | synduce/Synduce | mul.ml | type 'a tree =
| TNil
| TNode of 'a * 'a tree * 'a tree
type 'a list =
| LNil
| Cons of 'a * 'a list
type 'a ptree =
| PNil
| PNode of 'a * 'a ptree list
let rec target = function
| PNil -> 1
| PNode (a, l) -> [%synt join] a (prod l)
and prod = function
| LNil -> 1
| Cons (hd, tl) -> [%synt j2] (target hd) (prod tl)
;;
let rec spec = function
| TNil -> 1
| TNode (a, l, r) -> a * spec l * spec r
;;
let rec repr = function
| PNil -> TNil
| PNode (a, l) -> TNode (a, TNil, f l)
and f = function
| LNil -> TNil
| Cons (hd, tl) -> TNode (1, repr hd, f tl)
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/11e9eb1d420113ae85ec63399dd493034c51a354/benchmarks/ptree/mul.ml | ocaml | type 'a tree =
| TNil
| TNode of 'a * 'a tree * 'a tree
type 'a list =
| LNil
| Cons of 'a * 'a list
type 'a ptree =
| PNil
| PNode of 'a * 'a ptree list
let rec target = function
| PNil -> 1
| PNode (a, l) -> [%synt join] a (prod l)
and prod = function
| LNil -> 1
| Cons (hd, tl) -> [%synt j2] (target hd) (prod tl)
;;
let rec spec = function
| TNil -> 1
| TNode (a, l, r) -> a * spec l * spec r
;;
let rec repr = function
| PNil -> TNil
| PNode (a, l) -> TNode (a, TNil, f l)
and f = function
| LNil -> TNil
| Cons (hd, tl) -> TNode (1, repr hd, f tl)
;;
| |
9e11f783104cfdbd9e2699ce21158d46b1244883c7da46713323f031b8194b4b | Helium4Haskell/helium | Lambda1.hs |
main :: Bool -> ()
main = \True -> ()
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticwarnings/Lambda1.hs | haskell |
main :: Bool -> ()
main = \True -> ()
| |
0a22b26a5c9d01f28827d6375c6742e538cfc67ef4ff3effd6913360556cb15e | puppetlabs/clj-i18n | overlapping-packages.clj | ;; This is a sample of the locales.clj file that the current version fo the
;; Makefile generates.
It is used by the tests in core_test.clj .
{
:locales #{"es"}
alt3rnate3.i18n has the same length as , dexample.i18n . * overlaps with multi-package-es.clj
:packages ["example.i18n.another_package" "example" "example.i18n.another_package" "alt3rnat3.i18n"]
:bundle "overlapped_package.i18n.Messages"
}
| null | https://raw.githubusercontent.com/puppetlabs/clj-i18n/3f56f2b2be40aacd2dae09f32d5e6f97a12c363b/dev-resources/test-locales/overlapping-packages.clj | clojure | This is a sample of the locales.clj file that the current version fo the
Makefile generates. | It is used by the tests in core_test.clj .
{
:locales #{"es"}
alt3rnate3.i18n has the same length as , dexample.i18n . * overlaps with multi-package-es.clj
:packages ["example.i18n.another_package" "example" "example.i18n.another_package" "alt3rnat3.i18n"]
:bundle "overlapped_package.i18n.Messages"
}
|
aa78ea9bc839258120a201a58642159788f51d5bf097a0825da42e92ddf17843 | avsm/mirage-duniverse | handshake_server.mli | open State
val hello_request : handshake_state -> handshake_return eff
val handle_change_cipher_spec : server_handshake_state -> handshake_state -> Cstruct.t -> handshake_return eff
val handle_handshake : server_handshake_state -> handshake_state -> Cstruct.t -> handshake_return eff
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tls/lib/handshake_server.mli | ocaml | open State
val hello_request : handshake_state -> handshake_return eff
val handle_change_cipher_spec : server_handshake_state -> handshake_state -> Cstruct.t -> handshake_return eff
val handle_handshake : server_handshake_state -> handshake_state -> Cstruct.t -> handshake_return eff
| |
610acfde51af9d910749a74abb762dae3e8a1492d18f2e898f6b4c39e6c55281 | haskell/wreq | JsonResponse.hs | -- Examples of handling for JSON responses
--
-- This library provides several ways to handle JSON responses
# LANGUAGE DeriveGeneric , OverloadedStrings , ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - unused - binds #
import Control.Lens ((&), (^.), (^?), (.~))
import Data.Aeson (FromJSON)
import Data.Aeson.Lens (key)
import Data.Map (Map)
import Data.Text (Text)
import GHC.Generics (Generic)
import qualified Control.Exception as E
import Network.Wreq
This type corresponds to the structure of a response body
-- from httpbin.org.
data GetBody = GetBody {
headers :: Map Text Text
, args :: Map Text Text
, origin :: Text
, url :: Text
} deriving (Show, Generic)
Get GHC to derive a FromJSON instance for us .
instance FromJSON GetBody
-- We expect this to succeed.
basic_asJSON :: IO ()
basic_asJSON = do
let opts = defaults & param "foo" .~ ["bar"]
r <- asJSON =<< getWith opts ""
-- The fact that we want a GetBody here will be inferred by our use
-- of the "headers" accessor function.
putStrLn $ "args: " ++ show (args (r ^. responseBody))
-- The response we expect here is valid JSON, but cannot be converted
to an [ Int ] , so this will throw a JSONError .
failing_asJSON :: IO ()
failing_asJSON = do
(r :: Response [Int]) <- asJSON =<< get ""
putStrLn $ "response: " ++ show (r ^. responseBody)
This demonstrates how to catch a JSONError .
failing_asJSON_catch :: IO ()
failing_asJSON_catch =
failing_asJSON `E.catch` \(e :: JSONError) -> print e
Because asJSON is parameterized over MonadThrow , we can use it with
-- other instances.
--
Here , instead of throwing an exception in the IO monad , we instead
-- evaluate the result as an Either:
--
-- * if the conversion fails, the Left constructor will contain
-- whatever exception describes the error
--
-- * if the conversion succeeds, the Right constructor will contain
-- the converted response
either_asJSON :: IO ()
either_asJSON = do
r <- get ""
This first conversion attempt will fail , but because we 're using
-- Either, it will not throw an exception that kills execution.
let failing = asJSON r :: Either E.SomeException (Response [Int])
print failing
Our second conversion attempt will succeed .
let succeeding = asJSON r :: Either E.SomeException (Response GetBody)
print succeeding
-- The lens package defines some handy combinators for use with the
-- aeson package, with which we can easily traverse parts of a JSON
-- response.
lens_aeson :: IO ()
lens_aeson = do
r <- get ""
print $ r ^? responseBody . key "headers" . key "User-Agent"
If we maintain the ResponseBody as a ByteString , the lens
-- combinators will have to convert the body to a Value every time
-- we start a new traversal.
-- When we need to poke at several parts of a response, it's more
-- efficient to use asValue to perform the conversion to a Value
-- once.
let opts = defaults & param "baz" .~ ["quux"]
v <- asValue =<< getWith opts ""
print $ v ^? responseBody . key "args" . key "baz"
main :: IO ()
main = do
basic_asJSON
failing_asJSON_catch
either_asJSON
lens_aeson
| null | https://raw.githubusercontent.com/haskell/wreq/2da0070625a680d5af59e36c3ca253ef6a80aea9/examples/JsonResponse.hs | haskell | Examples of handling for JSON responses
This library provides several ways to handle JSON responses
from httpbin.org.
We expect this to succeed.
The fact that we want a GetBody here will be inferred by our use
of the "headers" accessor function.
The response we expect here is valid JSON, but cannot be converted
other instances.
evaluate the result as an Either:
* if the conversion fails, the Left constructor will contain
whatever exception describes the error
* if the conversion succeeds, the Right constructor will contain
the converted response
Either, it will not throw an exception that kills execution.
The lens package defines some handy combinators for use with the
aeson package, with which we can easily traverse parts of a JSON
response.
combinators will have to convert the body to a Value every time
we start a new traversal.
When we need to poke at several parts of a response, it's more
efficient to use asValue to perform the conversion to a Value
once. |
# LANGUAGE DeriveGeneric , OverloadedStrings , ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - unused - binds #
import Control.Lens ((&), (^.), (^?), (.~))
import Data.Aeson (FromJSON)
import Data.Aeson.Lens (key)
import Data.Map (Map)
import Data.Text (Text)
import GHC.Generics (Generic)
import qualified Control.Exception as E
import Network.Wreq
This type corresponds to the structure of a response body
data GetBody = GetBody {
headers :: Map Text Text
, args :: Map Text Text
, origin :: Text
, url :: Text
} deriving (Show, Generic)
Get GHC to derive a FromJSON instance for us .
instance FromJSON GetBody
basic_asJSON :: IO ()
basic_asJSON = do
let opts = defaults & param "foo" .~ ["bar"]
r <- asJSON =<< getWith opts ""
putStrLn $ "args: " ++ show (args (r ^. responseBody))
to an [ Int ] , so this will throw a JSONError .
failing_asJSON :: IO ()
failing_asJSON = do
(r :: Response [Int]) <- asJSON =<< get ""
putStrLn $ "response: " ++ show (r ^. responseBody)
This demonstrates how to catch a JSONError .
failing_asJSON_catch :: IO ()
failing_asJSON_catch =
failing_asJSON `E.catch` \(e :: JSONError) -> print e
Because asJSON is parameterized over MonadThrow , we can use it with
Here , instead of throwing an exception in the IO monad , we instead
either_asJSON :: IO ()
either_asJSON = do
r <- get ""
This first conversion attempt will fail , but because we 're using
let failing = asJSON r :: Either E.SomeException (Response [Int])
print failing
Our second conversion attempt will succeed .
let succeeding = asJSON r :: Either E.SomeException (Response GetBody)
print succeeding
lens_aeson :: IO ()
lens_aeson = do
r <- get ""
print $ r ^? responseBody . key "headers" . key "User-Agent"
If we maintain the ResponseBody as a ByteString , the lens
let opts = defaults & param "baz" .~ ["quux"]
v <- asValue =<< getWith opts ""
print $ v ^? responseBody . key "args" . key "baz"
main :: IO ()
main = do
basic_asJSON
failing_asJSON_catch
either_asJSON
lens_aeson
|
94f03fd192ecf300b04d0b798c36a8b419819442b0c8bac330a7e6e977a5e551 | KULeuven-CS/CPL | IMPLICITREFS-CONT.rkt | #lang eopl
(require "syntax.rkt")
(provide (all-defined-out))
Semantics
;;; an expressed value is either a number, or a boolean.
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?)))
(define expval->string
(lambda (v)
(cases expval v
(num-val (num) (string-append "Number: " (number->string num)))
(bool-val (bool) (string-append "Boolean: " (if bool "#t" "#f")))
(proc-val (proc) "Procedure: {proc} "))))
;; proc? : SchemeVal -> Bool
;; procedure : Var * Exp * Env -> Proc
(define-datatype proc proc?
(procedure
(var symbol?)
(body expression?)
(env environment?)))
;; expval->num : ExpVal -> Int
Page : 70
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
;; expval->bool : ExpVal -> Bool
Page : 70
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
;; expval->proc : ExpVal -> Proc
(define expval->proc
(lambda (v)
(cases expval v
(proc-val (p) p)
(else (expval-extractor-error 'proc v)))))
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
;; Environments
(define-datatype environment environment?
(empty-env)
(extend-env
(bvar symbol?)
(bval expval?)
(saved-env environment?))
(extend-env-rec
(id symbol?)
(bvar symbol?)
(body expression?)
(saved-env environment?)))
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(eopl:error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec (p-name b-var p-body saved-env)
(if (eqv? search-sym p-name)
(proc-val (procedure b-var p-body env))
(apply-env saved-env search-sym))))))
;; init-env : () -> Env
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
;; (init-env) builds an environment in which i is bound to the
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
;; Continuations
Page : 148
(define identifier? symbol?)
(define-datatype continuation continuation?
(end-cont) ; [ ]
(zero1-cont
(saved-cont continuation?)) ; E[zero? [] ]
(let-exp-cont
(var identifier?)
(body expression?)
(saved-env environment?)
(saved-cont continuation?)) ; E[let var = [] in body]
(if-test-cont
(exp2 expression?)
(exp3 expression?)
(saved-env environment?)
E[if [ ] then exp1 else exp2 ]
(diff1-cont
(exp2 expression?)
(saved-env environment?)
(saved-cont continuation?)) ; E[ [] - exp2 ]
(diff2-cont
(val1 expval?)
E [ val1 - [ ] ]
(rator-cont
(rand expression?)
(saved-env environment?)
(saved-cont continuation?)) ; E[([] rand)]
(rand-cont
(val1 expval?)
(saved-cont continuation?))); E[(val1 [])]
; cont->string: Cont -> String
; prints the continuation as a program with a hole [ ]
(define (cont->string k) (cont->string-inner k "[ ]"))
; cont->string-inner: (k:Cont) -> (h:String) -> String
; prints the continuation k as a program with h put in the hole
(define (cont->string-inner k hole)
(cases continuation k
(end-cont () hole)
(zero1-cont
(k2)
(cont->string-inner
k2 (string-append "zero?(" hole ")" )))
(let-exp-cont
(var body saved-env saved-cont)
(cont->string-inner
saved-cont
(string-append "let " (symbol->string var) " = " hole " in <" (exp->string body) ">" )))
(if-test-cont
(exp2 exp3 saved-env saved-cont)
(cont->string-inner
saved-cont
(string-append "if " hole " then <" (exp->string exp2) "> else <" (exp->string exp3) ">" )))
(diff1-cont
(exp env k2)
(cont->string-inner
k2
(string-append "(" hole " - <" (exp->string exp) ">)" )))
(diff2-cont
(v1 k2)
(cont->string-inner
k2
(string-append "(" (number->string (expval->num v1)) " - " hole ")")))
(rator-cont
(rand env k2)
(cont->string-inner
k2
(string-append "(" hole " <" (exp->string rand) ">)" )))
(rand-cont
(v1 k2)
(cont->string-inner
k2
(string-append "({proc} " hole ) ))
))
;; Interpreter
;; apply-cont : Cont * ExpVal -> FinalAnswer
Page : 148
(define apply-cont
(lambda (cont val)
(display (string-append "Sending " (expval->string val) " to cc " (cont->string cont) "\n"))
(cases continuation cont
(end-cont ()
(begin
(eopl:printf
"End of computation.~%")
val))
(zero1-cont (saved-cont)
(apply-cont saved-cont
(bool-val
(zero? (expval->num val)))))
(let-exp-cont (var body saved-env saved-cont)
(value-of/k body
(extend-env var val saved-env) saved-cont))
(if-test-cont (exp2 exp3 saved-env saved-cont)
(if (expval->bool val)
(value-of/k exp2 saved-env saved-cont)
(value-of/k exp3 saved-env saved-cont)))
(diff1-cont (exp2 saved-env saved-cont)
(value-of/k exp2
saved-env (diff2-cont val saved-cont)))
(diff2-cont (val1 saved-cont)
(let ((num1 (expval->num val1))
(num2 (expval->num val)))
(apply-cont saved-cont
(num-val (- num1 num2)))))
(rator-cont (rand saved-env saved-cont)
(value-of/k rand saved-env
(rand-cont val saved-cont)))
(rand-cont (val1 saved-cont)
(let ((proc (expval->proc val1)))
(apply-procedure/k proc val saved-cont)))
)))
;; value-of-program : Program -> FinalAnswer
Page : 143 and 154
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of/k exp1 (init-env) (end-cont))))))
;; value-of/k : Exp * Env * Cont -> FinalAnswer
Page : 143 - -146 , and 154
(define value-of/k
(lambda (exp env cont)
(display (string-append "Evaluating " (exp->string exp) " in cc " (cont->string cont)))
(display "\n")
(cases expression exp
(const-exp (num) (apply-cont cont (num-val num)))
(var-exp (var) (apply-cont cont (apply-env env var)))
(proc-exp (var body)
(apply-cont cont
(proc-val (procedure var body env))))
(letrec-exp (p-name b-var p-body letrec-body)
(value-of/k letrec-body
(extend-env-rec p-name b-var p-body env)
cont))
(zero?-exp (exp1)
(value-of/k exp1 env
(zero1-cont cont)))
(let-exp (var exp1 body)
(value-of/k exp1 env
(let-exp-cont var body env cont)))
(if-exp (exp1 exp2 exp3)
(value-of/k exp1 env
(if-test-cont exp2 exp3 env cont)))
(diff-exp (exp1 exp2)
(value-of/k exp1 env
(diff1-cont exp2 env cont)))
(call-exp (rator rand)
(value-of/k rator env
(rator-cont rand env cont)))
)))
;; apply-procedure/k : Proc * ExpVal * Cont -> FinalAnswer
Page 152 and 155
(define apply-procedure/k
(lambda (proc1 arg cont)
(cases proc proc1
(procedure (var body saved-env)
(value-of/k body
(extend-env var arg saved-env)
cont)))))
| null | https://raw.githubusercontent.com/KULeuven-CS/CPL/0c62cca832edc43218ac63c4e8233e3c3f05d20a/chapter5/5.9%20IMPLICITREFS-CONT/IMPLICITREFS-CONT.rkt | racket | an expressed value is either a number, or a boolean.
proc? : SchemeVal -> Bool
procedure : Var * Exp * Env -> Proc
expval->num : ExpVal -> Int
expval->bool : ExpVal -> Bool
expval->proc : ExpVal -> Proc
Environments
init-env : () -> Env
(init-env) builds an environment in which i is bound to the
Continuations
[ ]
E[zero? [] ]
E[let var = [] in body]
E[ [] - exp2 ]
E[([] rand)]
E[(val1 [])]
cont->string: Cont -> String
prints the continuation as a program with a hole [ ]
cont->string-inner: (k:Cont) -> (h:String) -> String
prints the continuation k as a program with h put in the hole
Interpreter
apply-cont : Cont * ExpVal -> FinalAnswer
value-of-program : Program -> FinalAnswer
value-of/k : Exp * Env * Cont -> FinalAnswer
apply-procedure/k : Proc * ExpVal * Cont -> FinalAnswer | #lang eopl
(require "syntax.rkt")
(provide (all-defined-out))
Semantics
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?)))
(define expval->string
(lambda (v)
(cases expval v
(num-val (num) (string-append "Number: " (number->string num)))
(bool-val (bool) (string-append "Boolean: " (if bool "#t" "#f")))
(proc-val (proc) "Procedure: {proc} "))))
(define-datatype proc proc?
(procedure
(var symbol?)
(body expression?)
(env environment?)))
Page : 70
(define expval->num
(lambda (v)
(cases expval v
(num-val (num) num)
(else (expval-extractor-error 'num v)))))
Page : 70
(define expval->bool
(lambda (v)
(cases expval v
(bool-val (bool) bool)
(else (expval-extractor-error 'bool v)))))
(define expval->proc
(lambda (v)
(cases expval v
(proc-val (p) p)
(else (expval-extractor-error 'proc v)))))
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define-datatype environment environment?
(empty-env)
(extend-env
(bvar symbol?)
(bval expval?)
(saved-env environment?))
(extend-env-rec
(id symbol?)
(bvar symbol?)
(body expression?)
(saved-env environment?)))
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(eopl:error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec (p-name b-var p-body saved-env)
(if (eqv? search-sym p-name)
(proc-val (procedure b-var p-body env))
(apply-env saved-env search-sym))))))
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
Page : 148
(define identifier? symbol?)
(define-datatype continuation continuation?
(zero1-cont
(let-exp-cont
(var identifier?)
(body expression?)
(saved-env environment?)
(if-test-cont
(exp2 expression?)
(exp3 expression?)
(saved-env environment?)
E[if [ ] then exp1 else exp2 ]
(diff1-cont
(exp2 expression?)
(saved-env environment?)
(diff2-cont
(val1 expval?)
E [ val1 - [ ] ]
(rator-cont
(rand expression?)
(saved-env environment?)
(rand-cont
(val1 expval?)
(define (cont->string k) (cont->string-inner k "[ ]"))
(define (cont->string-inner k hole)
(cases continuation k
(end-cont () hole)
(zero1-cont
(k2)
(cont->string-inner
k2 (string-append "zero?(" hole ")" )))
(let-exp-cont
(var body saved-env saved-cont)
(cont->string-inner
saved-cont
(string-append "let " (symbol->string var) " = " hole " in <" (exp->string body) ">" )))
(if-test-cont
(exp2 exp3 saved-env saved-cont)
(cont->string-inner
saved-cont
(string-append "if " hole " then <" (exp->string exp2) "> else <" (exp->string exp3) ">" )))
(diff1-cont
(exp env k2)
(cont->string-inner
k2
(string-append "(" hole " - <" (exp->string exp) ">)" )))
(diff2-cont
(v1 k2)
(cont->string-inner
k2
(string-append "(" (number->string (expval->num v1)) " - " hole ")")))
(rator-cont
(rand env k2)
(cont->string-inner
k2
(string-append "(" hole " <" (exp->string rand) ">)" )))
(rand-cont
(v1 k2)
(cont->string-inner
k2
(string-append "({proc} " hole ) ))
))
Page : 148
(define apply-cont
(lambda (cont val)
(display (string-append "Sending " (expval->string val) " to cc " (cont->string cont) "\n"))
(cases continuation cont
(end-cont ()
(begin
(eopl:printf
"End of computation.~%")
val))
(zero1-cont (saved-cont)
(apply-cont saved-cont
(bool-val
(zero? (expval->num val)))))
(let-exp-cont (var body saved-env saved-cont)
(value-of/k body
(extend-env var val saved-env) saved-cont))
(if-test-cont (exp2 exp3 saved-env saved-cont)
(if (expval->bool val)
(value-of/k exp2 saved-env saved-cont)
(value-of/k exp3 saved-env saved-cont)))
(diff1-cont (exp2 saved-env saved-cont)
(value-of/k exp2
saved-env (diff2-cont val saved-cont)))
(diff2-cont (val1 saved-cont)
(let ((num1 (expval->num val1))
(num2 (expval->num val)))
(apply-cont saved-cont
(num-val (- num1 num2)))))
(rator-cont (rand saved-env saved-cont)
(value-of/k rand saved-env
(rand-cont val saved-cont)))
(rand-cont (val1 saved-cont)
(let ((proc (expval->proc val1)))
(apply-procedure/k proc val saved-cont)))
)))
Page : 143 and 154
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of/k exp1 (init-env) (end-cont))))))
Page : 143 - -146 , and 154
(define value-of/k
(lambda (exp env cont)
(display (string-append "Evaluating " (exp->string exp) " in cc " (cont->string cont)))
(display "\n")
(cases expression exp
(const-exp (num) (apply-cont cont (num-val num)))
(var-exp (var) (apply-cont cont (apply-env env var)))
(proc-exp (var body)
(apply-cont cont
(proc-val (procedure var body env))))
(letrec-exp (p-name b-var p-body letrec-body)
(value-of/k letrec-body
(extend-env-rec p-name b-var p-body env)
cont))
(zero?-exp (exp1)
(value-of/k exp1 env
(zero1-cont cont)))
(let-exp (var exp1 body)
(value-of/k exp1 env
(let-exp-cont var body env cont)))
(if-exp (exp1 exp2 exp3)
(value-of/k exp1 env
(if-test-cont exp2 exp3 env cont)))
(diff-exp (exp1 exp2)
(value-of/k exp1 env
(diff1-cont exp2 env cont)))
(call-exp (rator rand)
(value-of/k rator env
(rator-cont rand env cont)))
)))
Page 152 and 155
(define apply-procedure/k
(lambda (proc1 arg cont)
(cases proc proc1
(procedure (var body saved-env)
(value-of/k body
(extend-env var arg saved-env)
cont)))))
|
bee90f5b7b190e45889007946ad77a3a9bae68d9cbd250a060ada395a47f30e1 | semilin/layoup | adept.lisp |
(MAKE-LAYOUT :NAME "adept" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL
:KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/adept.lisp | lisp |
(MAKE-LAYOUT :NAME "adept" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL
:KEYBOARD NIL) | |
fb56ce67c0f55d1271977f0f684e2505c4d3a789ed58be599a15dbe39ccbd1a8 | fossas/fossa-cli | DumpBinaries.hs | module App.Fossa.DumpBinaries (
dumpSubCommand,
) where
import App.Fossa.Config.DumpBinaries (
DumpBinsConfig (..),
DumpBinsOpts,
mkSubCommand,
)
import App.Fossa.EmbeddedBinary (allBins, dumpEmbeddedBinary)
import App.Fossa.Subcommand (SubCommand)
import Control.Effect.Lift (Has, Lift)
import Data.Foldable (for_)
dumpSubCommand :: SubCommand DumpBinsOpts DumpBinsConfig
dumpSubCommand = mkSubCommand dumpBinsMain
dumpBinsMain :: Has (Lift IO) sig m => DumpBinsConfig -> m ()
dumpBinsMain (DumpBinsConfig dir) = for_ allBins $ dumpEmbeddedBinary dir
| null | https://raw.githubusercontent.com/fossas/fossa-cli/756a76f02f53f28cfc05e799aa6d474cc8da2d20/src/App/Fossa/DumpBinaries.hs | haskell | module App.Fossa.DumpBinaries (
dumpSubCommand,
) where
import App.Fossa.Config.DumpBinaries (
DumpBinsConfig (..),
DumpBinsOpts,
mkSubCommand,
)
import App.Fossa.EmbeddedBinary (allBins, dumpEmbeddedBinary)
import App.Fossa.Subcommand (SubCommand)
import Control.Effect.Lift (Has, Lift)
import Data.Foldable (for_)
dumpSubCommand :: SubCommand DumpBinsOpts DumpBinsConfig
dumpSubCommand = mkSubCommand dumpBinsMain
dumpBinsMain :: Has (Lift IO) sig m => DumpBinsConfig -> m ()
dumpBinsMain (DumpBinsConfig dir) = for_ allBins $ dumpEmbeddedBinary dir
| |
447cb88623c31b3b5411c0ef41dec31bebb144b37ea689de4db15ac7cb40b049 | racket/math | flonum-search.rkt | #lang typed/racket/base
(require "flonum-constants.rkt"
"flonum-functions.rkt"
"flonum-bits.rkt")
(provide find-least-flonum flfind-least-integer)
(define +inf-ordinal (flonum->ordinal +inf.0))
(: find-least-flonum (case-> ((Flonum -> Any) Flonum -> (U Flonum #f))
((Flonum -> Any) Flonum Flonum -> (U Flonum #f))))
(define find-least-flonum
(case-lambda
[(pred? x-start)
(when (eqv? +nan.0 x-start)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 1 pred? x-start))
(let loop ([n-end (flonum->ordinal x-start)] [step 1])
(define x-end (ordinal->flonum n-end))
(cond [(pred? x-end) (find-least-flonum pred? x-start x-end)]
[(fl= x-end +inf.0) #f]
[else (loop (min +inf-ordinal (+ n-end step)) (* step 2))]))]
[(pred? x-start x-end)
(when (eqv? x-start +nan.0)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 1 pred? x-start x-end))
(when (eqv? x-end +nan.0)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 2 pred? x-start x-end))
(cond [(pred? x-start) x-start]
[(not (pred? x-end)) #f]
[else
(let loop ([n-start (flonum->ordinal x-start)] [n-end (flonum->ordinal x-end)])
(cond [(= n-start n-end) (define x (ordinal->flonum n-end))
(if (pred? x) x #f)]
[else
(define n-mid (quotient (+ n-start n-end) 2))
(cond [(pred? (ordinal->flonum n-mid))
(loop n-start n-mid)]
[else
(loop (+ n-mid 1) n-end)])]))])]))
(: sub-or-prev (Flonum Flonum -> Flonum))
(define (sub-or-prev k i)
(define prev-k (fl- k i))
(if (fl= prev-k k) (flprev* k) prev-k))
(: add-or-next (Flonum Flonum -> Flonum))
(define (add-or-next k i)
(define next-k (fl+ k i))
(if (fl= next-k k) (flnext* k) next-k))
(: flmidpoint (Flonum Flonum -> Flonum))
(define (flmidpoint x y)
(let ([x (flmin x y)]
[y (flmax x y)])
(cond [(fl= x -inf.0) (cond [(fl= y +inf.0) 0.0]
[(fl= y -inf.0) -inf.0]
[else (+ (* 0.5 -max.0) (* 0.5 y))])]
[(fl= y +inf.0) (cond [(fl= x +inf.0) +inf.0]
[else (+ (* 0.5 x) (* 0.5 +max.0))])]
[else (+ (* 0.5 x) (* 0.5 y))])))
(: flfind-least-integer (case-> ((Flonum -> Any) -> Flonum)
((Flonum -> Any) Flonum -> Flonum)
((Flonum -> Any) Flonum Flonum -> Flonum)
((Flonum -> Any) Flonum Flonum Flonum -> Flonum)))
;; Finds the least integer k such that (pred? k) is #t, given optional bounds and an optional
;; initial estimate. If the predicate is not monotone in the bounds, the result of this function is
;; indeterminate, and depends in an unspecified way on the initial estimate.
Formally , to get a unique answer , one of the following cases must be true .
1 . Exists k , forall mn < = i < k , ( pred ? i ) is # f /\ forall k < = j < = mx , ( pred ? j ) is # t
2 . Forall k , ( pred ? k ) is # f
3 . Forall k , ( pred ? k ) is # t
where mn0 < = k < = mx0 . For case # 1 , this function returns k. For case # 2 , it returns + nan.0 . For
case # 3 , it returns mn0 .
(define (flfind-least-integer pred? [mn0 -inf.0] [mx0 +inf.0] [k0 +nan.0])
(let ([mn (flceiling (flmin mn0 mx0))]
[mx (flfloor (flmax mn0 mx0))])
;; Make sure the initial estimate is in-bounds
(define k (cond [(and (k0 . >= . mn) (k0 . <= . mx)) (flfloor k0)]
[else (flfloor (flmidpoint mn mx))]))
(define k? (pred? k))
;; Find an integer k-min <= k for which (pred? k-min) is #f; increment exponentially
(define-values (k-min k-min?)
(let: loop : (Values Flonum Any) ([k-min : Flonum k] [k-min? : Any k?] [i : Flonum 1.0])
;(printf "min: ~v~n" k-min)
(cond [(k-min . fl<= . mn) (cond [(fl= k-min mn) (values k-min k-min?)]
[else (values mn (pred? mn))])]
[k-min? (define prev-k-min (sub-or-prev k-min i))
(loop prev-k-min (pred? prev-k-min) (* 2.0 (- k-min prev-k-min)))]
[else (values k-min #f)])))
Find an integer k - max > = k0 for which ( pred ? ) is # t ; increment exponentially
(define-values (k-max k-max?)
(let: loop : (Values Flonum Any) ([k-max : Flonum k] [k-max? : Any k?] [i : Flonum 1.0])
;(printf "max: ~v~n" k-max)
(cond [(k-max . fl>= . mx) (cond [(fl= k-max mx) (values k-max k-max?)]
[else (values mx (pred? mx))])]
[k-max? (values k-max #t)]
[else (define next-k-max (add-or-next k-max i))
(loop next-k-max (pred? next-k-max) (* 2.0 (- next-k-max k-max)))])))
Quickly check cases # 2 and # 3 ; if case # 1 , do a binary search
(cond [(not k-max?) +nan.0]
[k-min? mn]
[else
Loop invariant : ( pred ? ) is # t and ( pred ? k - min ) is # f
(let loop ([k-min k-min] [k-max k-max])
;(printf "~v ~v~n" k-min k-max)
(define k (flfloor (flmidpoint k-min k-max)))
;; Check whether k-min + 1 = k-max or (flnext k-min) = k-max
(cond [(or (= k k-min) (= k k-max)) k-max]
[(pred? k) (loop k-min k)]
[else (loop k k-max)]))])))
| null | https://raw.githubusercontent.com/racket/math/dcd2ea1893dc5b45b26c8312997917a15fcd1c4a/math-lib/math/private/flonum/flonum-search.rkt | racket | Finds the least integer k such that (pred? k) is #t, given optional bounds and an optional
initial estimate. If the predicate is not monotone in the bounds, the result of this function is
indeterminate, and depends in an unspecified way on the initial estimate.
Make sure the initial estimate is in-bounds
Find an integer k-min <= k for which (pred? k-min) is #f; increment exponentially
(printf "min: ~v~n" k-min)
increment exponentially
(printf "max: ~v~n" k-max)
if case # 1 , do a binary search
(printf "~v ~v~n" k-min k-max)
Check whether k-min + 1 = k-max or (flnext k-min) = k-max | #lang typed/racket/base
(require "flonum-constants.rkt"
"flonum-functions.rkt"
"flonum-bits.rkt")
(provide find-least-flonum flfind-least-integer)
(define +inf-ordinal (flonum->ordinal +inf.0))
(: find-least-flonum (case-> ((Flonum -> Any) Flonum -> (U Flonum #f))
((Flonum -> Any) Flonum Flonum -> (U Flonum #f))))
(define find-least-flonum
(case-lambda
[(pred? x-start)
(when (eqv? +nan.0 x-start)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 1 pred? x-start))
(let loop ([n-end (flonum->ordinal x-start)] [step 1])
(define x-end (ordinal->flonum n-end))
(cond [(pred? x-end) (find-least-flonum pred? x-start x-end)]
[(fl= x-end +inf.0) #f]
[else (loop (min +inf-ordinal (+ n-end step)) (* step 2))]))]
[(pred? x-start x-end)
(when (eqv? x-start +nan.0)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 1 pred? x-start x-end))
(when (eqv? x-end +nan.0)
(raise-argument-error 'find-least-flonum "non-NaN Flonum" 2 pred? x-start x-end))
(cond [(pred? x-start) x-start]
[(not (pred? x-end)) #f]
[else
(let loop ([n-start (flonum->ordinal x-start)] [n-end (flonum->ordinal x-end)])
(cond [(= n-start n-end) (define x (ordinal->flonum n-end))
(if (pred? x) x #f)]
[else
(define n-mid (quotient (+ n-start n-end) 2))
(cond [(pred? (ordinal->flonum n-mid))
(loop n-start n-mid)]
[else
(loop (+ n-mid 1) n-end)])]))])]))
(: sub-or-prev (Flonum Flonum -> Flonum))
(define (sub-or-prev k i)
(define prev-k (fl- k i))
(if (fl= prev-k k) (flprev* k) prev-k))
(: add-or-next (Flonum Flonum -> Flonum))
(define (add-or-next k i)
(define next-k (fl+ k i))
(if (fl= next-k k) (flnext* k) next-k))
(: flmidpoint (Flonum Flonum -> Flonum))
(define (flmidpoint x y)
(let ([x (flmin x y)]
[y (flmax x y)])
(cond [(fl= x -inf.0) (cond [(fl= y +inf.0) 0.0]
[(fl= y -inf.0) -inf.0]
[else (+ (* 0.5 -max.0) (* 0.5 y))])]
[(fl= y +inf.0) (cond [(fl= x +inf.0) +inf.0]
[else (+ (* 0.5 x) (* 0.5 +max.0))])]
[else (+ (* 0.5 x) (* 0.5 y))])))
(: flfind-least-integer (case-> ((Flonum -> Any) -> Flonum)
((Flonum -> Any) Flonum -> Flonum)
((Flonum -> Any) Flonum Flonum -> Flonum)
((Flonum -> Any) Flonum Flonum Flonum -> Flonum)))
Formally , to get a unique answer , one of the following cases must be true .
1 . Exists k , forall mn < = i < k , ( pred ? i ) is # f /\ forall k < = j < = mx , ( pred ? j ) is # t
2 . Forall k , ( pred ? k ) is # f
3 . Forall k , ( pred ? k ) is # t
where mn0 < = k < = mx0 . For case # 1 , this function returns k. For case # 2 , it returns + nan.0 . For
case # 3 , it returns mn0 .
(define (flfind-least-integer pred? [mn0 -inf.0] [mx0 +inf.0] [k0 +nan.0])
(let ([mn (flceiling (flmin mn0 mx0))]
[mx (flfloor (flmax mn0 mx0))])
(define k (cond [(and (k0 . >= . mn) (k0 . <= . mx)) (flfloor k0)]
[else (flfloor (flmidpoint mn mx))]))
(define k? (pred? k))
(define-values (k-min k-min?)
(let: loop : (Values Flonum Any) ([k-min : Flonum k] [k-min? : Any k?] [i : Flonum 1.0])
(cond [(k-min . fl<= . mn) (cond [(fl= k-min mn) (values k-min k-min?)]
[else (values mn (pred? mn))])]
[k-min? (define prev-k-min (sub-or-prev k-min i))
(loop prev-k-min (pred? prev-k-min) (* 2.0 (- k-min prev-k-min)))]
[else (values k-min #f)])))
(define-values (k-max k-max?)
(let: loop : (Values Flonum Any) ([k-max : Flonum k] [k-max? : Any k?] [i : Flonum 1.0])
(cond [(k-max . fl>= . mx) (cond [(fl= k-max mx) (values k-max k-max?)]
[else (values mx (pred? mx))])]
[k-max? (values k-max #t)]
[else (define next-k-max (add-or-next k-max i))
(loop next-k-max (pred? next-k-max) (* 2.0 (- next-k-max k-max)))])))
(cond [(not k-max?) +nan.0]
[k-min? mn]
[else
Loop invariant : ( pred ? ) is # t and ( pred ? k - min ) is # f
(let loop ([k-min k-min] [k-max k-max])
(define k (flfloor (flmidpoint k-min k-max)))
(cond [(or (= k k-min) (= k k-max)) k-max]
[(pred? k) (loop k-min k)]
[else (loop k k-max)]))])))
|
bab048981bd3be712f799d102a89bd820bbf493085f2025beabe914721584e81 | vyos/vyconf | vylist_test.ml | open OUnit2
open Vylist
(* Searching for an element that is in the list gives Some that_element *)
let test_find_existent test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (find (fun x -> x = 3) xs) (Some 3)
(* Searching for an element that is not in the list gives None *)
let test_find_nonexistent test_ctxt =
let xs = [1; 2; 4] in
assert_equal (find (fun x -> x = 3) xs) None
(* Removing an element that exists in the list makes a list without that element *)
let test_remove_existent test_ctct =
let xs = [1; 2; 3; 4] in
assert_equal (remove (fun x -> x = 3) xs) [1; 2; 4]
(* Trying to remove an element that is not in the list doesn't change the list *)
let test_remove_nonexistent test_ctct =
let xs = [1; 2; 4] in
assert_equal (remove (fun x -> x = 3) xs) [1; 2; 4]
(* Replacing an element works *)
let test_replace_element_existent test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (replace ((=) 3) 7 xs) [1; 2; 7; 4]
(* Attempt to replace a nonexistent element causes an exception *)
let test_replace_element_nonexistent test_ctxt =
let xs = [1; 2; 3] in
assert_raises Not_found (fun () -> replace ((=) 4) 7 xs)
(* insert_before works if the element is there *)
let test_insert_before_existent test_ctxt =
let xs = [1; 2; 3] in
assert_equal (insert_before ((=) 2) 7 xs) [1; 7; 2; 3]
(* insert_before raises Not_found if there's not such element *)
let test_insert_before_nonexistent test_ctxt =
let xs = [1; 2; 3] in
assert_raises Not_found (fun () -> insert_before ((=) 9) 7 xs)
complement returns correct result when one list contains another , in any order
let test_complement_first_is_longer test_ctxt =
let xs = [1; 2; 3; 4; 5] and ys = [1; 2; 3] in
assert_equal (complement xs ys) [4; 5]
let test_complement_second_is_longer test_ctxt =
let xs = [1; 2] and ys = [1; 2; 3; 4; 5] in
assert_equal (complement xs ys) [3; 4; 5]
complement returns an empty list if one list does n't contain another
let test_complement_doesnt_contain test_ctxt =
let xs = [1; 2; 3] and ys = [1; 4; 5; 6] in
assert_equal (complement xs ys) []
(* in_list works *)
let test_in_list test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (in_list xs 3) true;
assert_equal (in_list xs 9) false
let suite =
"VyConf list tests" >::: [
"test_find_existent" >:: test_find_existent;
"test_find_nonexistent" >:: test_find_nonexistent;
"test_remove_existent" >:: test_remove_existent;
"test_remove_nonexistent" >:: test_remove_nonexistent;
"test_replace_element_existent" >:: test_replace_element_existent;
"test_replace_element_nonexistent" >:: test_replace_element_nonexistent;
"test_insert_before_existent" >:: test_insert_before_existent;
"test_insert_before_nonexistent" >:: test_insert_before_nonexistent;
"test_complement_first_is_longer" >:: test_complement_first_is_longer;
"test_complement_second_is_longer" >:: test_complement_second_is_longer;
"test_complement_doesnt_contain" >:: test_complement_doesnt_contain;
"test_in_list" >:: test_in_list;
]
let () =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/vyos/vyconf/dd9271b4304c6b1a5a2576821d1b2b8fd3aa6bf5/test/vylist_test.ml | ocaml | Searching for an element that is in the list gives Some that_element
Searching for an element that is not in the list gives None
Removing an element that exists in the list makes a list without that element
Trying to remove an element that is not in the list doesn't change the list
Replacing an element works
Attempt to replace a nonexistent element causes an exception
insert_before works if the element is there
insert_before raises Not_found if there's not such element
in_list works | open OUnit2
open Vylist
let test_find_existent test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (find (fun x -> x = 3) xs) (Some 3)
let test_find_nonexistent test_ctxt =
let xs = [1; 2; 4] in
assert_equal (find (fun x -> x = 3) xs) None
let test_remove_existent test_ctct =
let xs = [1; 2; 3; 4] in
assert_equal (remove (fun x -> x = 3) xs) [1; 2; 4]
let test_remove_nonexistent test_ctct =
let xs = [1; 2; 4] in
assert_equal (remove (fun x -> x = 3) xs) [1; 2; 4]
let test_replace_element_existent test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (replace ((=) 3) 7 xs) [1; 2; 7; 4]
let test_replace_element_nonexistent test_ctxt =
let xs = [1; 2; 3] in
assert_raises Not_found (fun () -> replace ((=) 4) 7 xs)
let test_insert_before_existent test_ctxt =
let xs = [1; 2; 3] in
assert_equal (insert_before ((=) 2) 7 xs) [1; 7; 2; 3]
let test_insert_before_nonexistent test_ctxt =
let xs = [1; 2; 3] in
assert_raises Not_found (fun () -> insert_before ((=) 9) 7 xs)
complement returns correct result when one list contains another , in any order
let test_complement_first_is_longer test_ctxt =
let xs = [1; 2; 3; 4; 5] and ys = [1; 2; 3] in
assert_equal (complement xs ys) [4; 5]
let test_complement_second_is_longer test_ctxt =
let xs = [1; 2] and ys = [1; 2; 3; 4; 5] in
assert_equal (complement xs ys) [3; 4; 5]
complement returns an empty list if one list does n't contain another
let test_complement_doesnt_contain test_ctxt =
let xs = [1; 2; 3] and ys = [1; 4; 5; 6] in
assert_equal (complement xs ys) []
let test_in_list test_ctxt =
let xs = [1; 2; 3; 4] in
assert_equal (in_list xs 3) true;
assert_equal (in_list xs 9) false
let suite =
"VyConf list tests" >::: [
"test_find_existent" >:: test_find_existent;
"test_find_nonexistent" >:: test_find_nonexistent;
"test_remove_existent" >:: test_remove_existent;
"test_remove_nonexistent" >:: test_remove_nonexistent;
"test_replace_element_existent" >:: test_replace_element_existent;
"test_replace_element_nonexistent" >:: test_replace_element_nonexistent;
"test_insert_before_existent" >:: test_insert_before_existent;
"test_insert_before_nonexistent" >:: test_insert_before_nonexistent;
"test_complement_first_is_longer" >:: test_complement_first_is_longer;
"test_complement_second_is_longer" >:: test_complement_second_is_longer;
"test_complement_doesnt_contain" >:: test_complement_doesnt_contain;
"test_in_list" >:: test_in_list;
]
let () =
run_test_tt_main suite
|
1476b775f384e36b11fb1ad26d039751abdf3cdc85d43c6c093b4f7ee494b3ba | syntax-objects/syntax-parse-example | multi-check-true-test.rkt | #lang racket/base
(module+ test
(require rackunit syntax-parse-example/multi-check-true/multi-check-true)
(multi-check-true
#t
(and #true #true)
(or #false #true)
(= 4 (+ 2 2)))
)
| null | https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0675ce0717369afcde284202ec7df661d7af35aa/multi-check-true/multi-check-true-test.rkt | racket | #lang racket/base
(module+ test
(require rackunit syntax-parse-example/multi-check-true/multi-check-true)
(multi-check-true
#t
(and #true #true)
(or #false #true)
(= 4 (+ 2 2)))
)
| |
b7a20f6d59bab66a3db4aa5c336c3bc97e7e46571dd1c65da5e5d18865369cd7 | askvortsov1/hardcaml-mips | test_memory.ml | open Hardcaml
open Hardcaml_waveterm
open Mips.Memory
module Simulator = Cyclesim.With_interface (I) (O)
type test_input = {
write_enable : string;
write_data : string;
data_address : string;
}
let testbench () =
let scope = Scope.create ~flatten_design:true () in
let sim = Simulator.create (circuit_impl scope) in
let waves, sim = Waveform.create sim in
let inputs = Cyclesim.inputs sim in
let step ~test =
inputs.write_enable := Bits.of_string test.write_enable;
inputs.read_addr := Bits.of_string test.data_address;
inputs.write_addr := Bits.of_string test.data_address;
inputs.write_data := Bits.of_string test.write_data;
Cyclesim.cycle sim
in
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h7" };
alu_a should now be 8 after this step
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h6" };
(* Memory should be 0 since everything has been disabled so far *)
step
~test:
{ write_enable = "1'h1"; data_address = "32'h9"; write_data = "32'h86" };
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h6" };
Now we can read what we wrote .
* It 's delayed by a stage since the simulator is n't half - cycle accurate
* ( see test_instruction_decode for more details ) but we do n't care about
* that for data memory .
* It's delayed by a stage since the simulator isn't half-cycle accurate
* (see test_instruction_decode for more details) but we don't care about
* that for data memory.
*)
waves
let%expect_test "can we read and write to/from data memory properly" =
let waves = testbench () in
Waveform.print ~wave_width:4 ~display_width:90 ~display_height:35 waves;
[%expect
{|
┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────────┐
│clock ││┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
│ ││ └────┘ └────┘ └────┘ └────┘ └────┘ └────┘ └──│
│ ││──────────────────────────────────────── │
│read_addr ││ 00000009 │
│ ││──────────────────────────────────────── │
│ ││──────────────────────────────────────── │
│write_addr ││ 00000009 │
│ ││──────────────────────────────────────── │
│ ││──────────┬─────────┬─────────┬───────── │
│write_data ││ 00000007 │00000006 │00000086 │00000006 │
│ ││──────────┴─────────┴─────────┴───────── │
│write_enable ││ ┌─────────┐ │
│ ││────────────────────┘ └───────── │
│io_busy ││ │
│ ││──────────────────────────────────────── │
│ ││──────────────────────────────┬───────── │
│read_data ││ 00000000 │00000086 │
│ ││──────────────────────────────┴───────── │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└──────────────────┘└────────────────────────────────────────────────────────────────────┘ |}]
| null | https://raw.githubusercontent.com/askvortsov1/hardcaml-mips/c94e0a8907ba4214f05e615a8e1407acc1777f15/test/io/test_memory.ml | ocaml | Memory should be 0 since everything has been disabled so far | open Hardcaml
open Hardcaml_waveterm
open Mips.Memory
module Simulator = Cyclesim.With_interface (I) (O)
type test_input = {
write_enable : string;
write_data : string;
data_address : string;
}
let testbench () =
let scope = Scope.create ~flatten_design:true () in
let sim = Simulator.create (circuit_impl scope) in
let waves, sim = Waveform.create sim in
let inputs = Cyclesim.inputs sim in
let step ~test =
inputs.write_enable := Bits.of_string test.write_enable;
inputs.read_addr := Bits.of_string test.data_address;
inputs.write_addr := Bits.of_string test.data_address;
inputs.write_data := Bits.of_string test.write_data;
Cyclesim.cycle sim
in
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h7" };
alu_a should now be 8 after this step
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h6" };
step
~test:
{ write_enable = "1'h1"; data_address = "32'h9"; write_data = "32'h86" };
step
~test:
{ write_enable = "1'h0"; data_address = "32'h9"; write_data = "32'h6" };
Now we can read what we wrote .
* It 's delayed by a stage since the simulator is n't half - cycle accurate
* ( see test_instruction_decode for more details ) but we do n't care about
* that for data memory .
* It's delayed by a stage since the simulator isn't half-cycle accurate
* (see test_instruction_decode for more details) but we don't care about
* that for data memory.
*)
waves
let%expect_test "can we read and write to/from data memory properly" =
let waves = testbench () in
Waveform.print ~wave_width:4 ~display_width:90 ~display_height:35 waves;
[%expect
{|
┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────────┐
│clock ││┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
│ ││ └────┘ └────┘ └────┘ └────┘ └────┘ └────┘ └──│
│ ││──────────────────────────────────────── │
│read_addr ││ 00000009 │
│ ││──────────────────────────────────────── │
│ ││──────────────────────────────────────── │
│write_addr ││ 00000009 │
│ ││──────────────────────────────────────── │
│ ││──────────┬─────────┬─────────┬───────── │
│write_data ││ 00000007 │00000006 │00000086 │00000006 │
│ ││──────────┴─────────┴─────────┴───────── │
│write_enable ││ ┌─────────┐ │
│ ││────────────────────┘ └───────── │
│io_busy ││ │
│ ││──────────────────────────────────────── │
│ ││──────────────────────────────┬───────── │
│read_data ││ 00000000 │00000086 │
│ ││──────────────────────────────┴───────── │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└──────────────────┘└────────────────────────────────────────────────────────────────────┘ |}]
|
edd972b190212aa277af9f72c6839b1228c0876626e7cbc05fb62f4ff29b795f | fission-codes/fission | Types.hs | module Fission.Web.Server.MonadDB.Types (Transaction) where
import Database.Persist.Sql
import RIO
type Transaction m = ReaderT SqlBackend m
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/MonadDB/Types.hs | haskell | module Fission.Web.Server.MonadDB.Types (Transaction) where
import Database.Persist.Sql
import RIO
type Transaction m = ReaderT SqlBackend m
| |
762ea46a7acff6efec874d8b4ab4683e1038af0946074c66f07b5bc2f8d0256f | odis-labs/helix | Ppx.ml | Based on -re/melange/pull/396/files
module OCaml_Location = Location
open Ppxlib
module Helper = Ppxlib.Ast_helper
let pr fmt = Format.kasprintf (fun x -> prerr_endline x) fmt
module Builder = struct
Ast_builder . Default assigns attributes to be the empty .
This wrapper re - exports all used fns with attrs arg to override them .
This wrapper re-exports all used fns with attrs arg to override them. *)
include Ast_builder.Default
let pexp_apply ~loc ?(attrs = []) e args =
let e = Ast_builder.Default.pexp_apply ~loc e args in
{ e with pexp_attributes = attrs }
let value_binding ~loc ~pat ~expr ~attrs =
let vb = Ast_builder.Default.value_binding ~loc ~pat ~expr in
{ vb with pvb_attributes = attrs }
let value_description ~loc ~name ~type_ ~prim ~attrs =
let vd = Ast_builder.Default.value_description ~loc ~name ~type_ ~prim in
{ vd with pval_attributes = attrs }
end
module Jsx_runtime = struct
let elem name ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Elem"), name) }
let attr name ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), name) }
let null ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "null") }
let text ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "text") }
let int ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "int") }
let float ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "float") }
let fragment ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "fragment") }
let syntax_option1 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option1") }
let syntax_option2 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option2") }
let syntax_option3 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option3") }
end
let child_to_elem child =
let loc = child.pexp_loc in
match child.pexp_desc with
" str " = = > " )
| Pexp_constant (Pconst_string _) ->
Builder.pexp_apply ~loc (Jsx_runtime.text ~loc) [ (Nolabel, child) ]
42 = = > Jsx.int(42 )
| Pexp_constant (Pconst_integer _) ->
Builder.pexp_apply ~loc (Jsx_runtime.int ~loc) [ (Nolabel, child) ]
3.14 = = > Jsx.float(3.14 )
| Pexp_constant (Pconst_float _) ->
Builder.pexp_apply ~loc (Jsx_runtime.float ~loc) [ (Nolabel, child) ]
| _ -> child
let process_children ~loc ~mapper l0 =
let rec loop l acc =
match l.pexp_desc with
(* [] *)
| Pexp_construct ({ txt = Lident "[]"; _ }, None) -> (
match acc with
| [] -> `empty
| [ x ] -> `single (child_to_elem x)
| _ -> `array (Builder.pexp_array ~loc (List.rev_map child_to_elem acc)))
(* _::_ *)
| Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [ x; l' ]; _ })
-> loop l' (mapper#expression x :: acc)
(* not a list, XXX: is this possible? *)
| _not_a_list -> `single (mapper#expression l)
in
loop l0 []
let prop_to_apply ~loc:loc0 (arg_l, arg_e) =
match (arg_l, arg_e) with
? l:(val_1 , val_2 )
| ( Optional l
, { pexp_desc = Pexp_tuple [ val_1; val_2 ]
; pexp_loc = loc
; pexp_attributes
; pexp_loc_stack = _
} ) ->
let syn_fun = Jsx_runtime.syntax_option2 ~loc in
let syn_attr = Jsx_runtime.attr l ~loc in
Builder.pexp_apply ~loc:loc0 syn_fun ~attrs:pexp_attributes
[ (Nolabel, syn_attr); (Nolabel, val_1); (Nolabel, val_2) ]
? l:(val_1 , val_2 , val_3 )
| ( Optional l
, { pexp_desc = Pexp_tuple [ val_1; val_2; val_3 ]
; pexp_loc = loc
; pexp_attributes
; pexp_loc_stack = _
} ) ->
let syn_fun = Jsx_runtime.syntax_option3 ~loc in
let syn_attr = Jsx_runtime.attr l ~loc in
Builder.pexp_apply ~loc:loc0 syn_fun ~attrs:pexp_attributes
[ (Nolabel, syn_attr)
; (Nolabel, val_1)
; (Nolabel, val_2)
; (Nolabel, val_3)
]
? l :
| Optional l, val_1 ->
let syn_fun = Jsx_runtime.syntax_option1 ~loc:loc0 in
let syn_attr = Jsx_runtime.attr l ~loc:loc0 in
Builder.pexp_apply ~loc:loc0 syn_fun
[ (Nolabel, syn_attr); (Nolabel, val_1) ]
(* ~l *)
| Labelled l, _ ->
let attr_fun = Jsx_runtime.attr l ~loc:loc0 in
Builder.pexp_apply ~loc:loc0 attr_fun [ (Nolabel, arg_e) ]
| Nolabel, _ -> assert false
let prop_list_to_array ~loc (props : (arg_label * expression) list) =
let propsApplies = List.map (prop_to_apply ~loc) props in
Builder.pexp_array ~loc propsApplies
let extractChildren ?(removeLastPositionUnit = false) ~loc propsAndChildren =
let rec allButLast_ lst acc =
match lst with
| [] -> []
| [ ( Nolabel
, { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, None); _ } )
] -> acc
| (Nolabel, _) :: _rest ->
raise
(Invalid_argument
"JSX: found non-labelled argument before the last position")
| arg :: rest -> allButLast_ rest (arg :: acc)
[@@raises Invalid_argument]
in
let allButLast lst =
allButLast_ lst [] |> List.rev
[@@raises Invalid_argument]
in
match
List.partition
(fun (label, _) -> label = Labelled "children")
propsAndChildren
with
| [], props ->
(* no children provided? Place a placeholder list *)
( Builder.pexp_construct ~loc { loc; txt = Lident "[]" } None
, if removeLastPositionUnit then allButLast props else props )
| [ (_, childrenExpr) ], props ->
(childrenExpr, if removeLastPositionUnit then allButLast props else props)
| _ ->
raise
(Invalid_argument "JSX: somehow there's more than one `children` label")
[@@raises Invalid_argument]
let get_label = function
| Nolabel -> ""
| Labelled l | Optional l -> l
(* TODO: some line number might still be wrong *)
let rewritter =
let transformUppercaseCall3 ~caller modulePath mapper loc attrs _
callArguments =
let children, argsWithLabels =
extractChildren ~loc ~removeLastPositionUnit:true callArguments
in
let argsForMake = argsWithLabels in
let children' =
match process_children ~loc ~mapper children with
| `empty -> Ast_helper.Exp.construct (Loc.make ~loc (Lident "()")) None
| `single e -> e
| `array e -> e
in
let recursivelyTransformedArgsForMake =
argsForMake
|> List.map (fun (label, expression) ->
(label, mapper#expression expression))
in
let props = recursivelyTransformedArgsForMake in
let isCap str =
let first = String.sub str 0 1 [@@raises Invalid_argument] in
let capped = String.uppercase_ascii first in
first = capped
[@@raises Invalid_argument]
in
let ident =
match modulePath with
| Lident _ -> Ldot (modulePath, caller)
| Ldot (_modulePath, value) as fullPath when isCap value ->
Ldot (fullPath, caller)
| modulePath -> modulePath
in
Builder.pexp_apply ~loc ~attrs
(Builder.pexp_ident ~loc { txt = ident; loc })
(props @ [ (Nolabel, children') ])
[@@raises Invalid_argument]
in
let transformLowercaseCall3 mapper loc attrs callArguments id =
let children, nonChildrenProps =
extractChildren ~removeLastPositionUnit:true ~loc callArguments
in
match (id, children.pexp_desc) with
(* text/int/float *)
| ( "text"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.text ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
| ( "int"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.int ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
| ( "float"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.float ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
(* [@JSX] div(~children=[a]), coming from <div> a </div> *)
| ( _
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple _; _ }) )
| _, Pexp_construct ({ txt = Lident "[]"; _ }, None) ->
let elem_f = Jsx_runtime.elem id ~loc in
let props =
nonChildrenProps
|> List.map (fun (label, e) -> (label, mapper#expression e))
|> prop_list_to_array ~loc
in
let children' =
match process_children ~loc ~mapper children with
| `empty -> Ast_helper.Exp.array ~loc []
| `single e -> Ast_helper.Exp.array ~loc [ e ]
| `array e -> e
in
let args =
[ |Jsx . ; bar| ]
(Nolabel, props)
; (* [|moreelem_fsHere|] *)
(Nolabel, children')
]
in
Builder.pexp_apply ~loc ~attrs elem_f args
(* [@JSX] div(~children=value), <div> ...(value) </div> *)
| _ ->
let elem_f = Jsx_runtime.elem id ~loc in
let props =
nonChildrenProps
|> List.map (fun (label, e) -> (label, mapper#expression e))
|> prop_list_to_array ~loc
in
let args =
[ |Jsx . ; bar| ]
(Nolabel, props)
; (* [|moreelem_fsHere|] *)
(Nolabel, children)
]
in
Builder.pexp_apply ~loc ~attrs elem_f args
in
let transform_jsx_apply mapper f_exp f_args attrs =
match f_exp.pexp_desc with
| Pexp_ident caller -> (
match caller with
| { txt = Lident "createElement"; _ } ->
raise
(Invalid_argument
"JSX: `createElement` should be preceeded by a module name.")
Foo.createElement(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) )
| { loc; txt = Ldot (mod_path, ("createElement" | "make")) } ->
transformUppercaseCall3 ~caller:"make" mod_path mapper loc attrs f_exp
f_args
div(~prop1 = foo , ~prop2 = bar , ~children=[bla ] , ( ) )
| { loc; txt = Lident id } ->
transformLowercaseCall3 mapper loc attrs f_args id
Foo.bar(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) )
| { loc; txt = Ldot (mod_path, f_non_std) } ->
transformUppercaseCall3 ~caller:f_non_std mod_path mapper loc attrs
f_exp f_args
| { txt = Lapply _; _ } ->
(* don't think there's ever a case where this is reached *)
raise
(Invalid_argument
"JSX: encountered a weird case while processing the code. Please \
report this!"))
| _ ->
raise
(Invalid_argument
"JSX: `createElement` should be preceeded by a simple, direct \
module name.")
[@@raises Invalid_argument]
in
object (mapper)
inherit Ast_traverse.map as super
method! expression exp =
match exp.pexp_desc with
(* Look for (f args [@JSX]) *)
| Pexp_apply (f_exp, f_args) -> (
let jsx_attrs, other_attrs =
List.partition
(fun attr -> attr.attr_name.txt = "JSX")
exp.pexp_attributes
in
match jsx_attrs with
| [] -> super#expression exp
| _ -> transform_jsx_apply mapper f_exp f_args other_attrs)
(* Fragment: <>foo</> as [@JSX][foo] *)
| Pexp_construct
({ txt = Lident "::"; loc; _ }, Some { pexp_desc = Pexp_tuple _; _ })
| Pexp_construct ({ txt = Lident "[]"; loc }, None) -> (
let jsx_attrs, other_attrs =
List.partition
(fun attr -> attr.attr_name.txt = "JSX")
exp.pexp_attributes
in
match jsx_attrs with
| [] -> super#expression exp
| _ ->
let children' =
match process_children ~loc ~mapper exp with
| `empty -> Ast_helper.Exp.array ~loc []
| `single e -> Ast_helper.Exp.array ~loc [ e ]
| `array e -> e
in
let args = [ (Nolabel, children') ] in
Builder.pexp_apply ~loc ~attrs:other_attrs
(Jsx_runtime.fragment ~loc)
args)
(* Other: use default mapper *)
| _ -> super#expression exp
[@@raises Invalid_argument]
end
let () =
Driver.register_transformation "helix-ppx" ~impl:rewritter#structure
~intf:rewritter#signature
| null | https://raw.githubusercontent.com/odis-labs/helix/05d59aa6c13621275c31953a3515ee8843508f9e/src/helix-ppx/Ppx.ml | ocaml | []
_::_
not a list, XXX: is this possible?
~l
no children provided? Place a placeholder list
TODO: some line number might still be wrong
text/int/float
[@JSX] div(~children=[a]), coming from <div> a </div>
[|moreelem_fsHere|]
[@JSX] div(~children=value), <div> ...(value) </div>
[|moreelem_fsHere|]
don't think there's ever a case where this is reached
Look for (f args [@JSX])
Fragment: <>foo</> as [@JSX][foo]
Other: use default mapper | Based on -re/melange/pull/396/files
module OCaml_Location = Location
open Ppxlib
module Helper = Ppxlib.Ast_helper
let pr fmt = Format.kasprintf (fun x -> prerr_endline x) fmt
module Builder = struct
Ast_builder . Default assigns attributes to be the empty .
This wrapper re - exports all used fns with attrs arg to override them .
This wrapper re-exports all used fns with attrs arg to override them. *)
include Ast_builder.Default
let pexp_apply ~loc ?(attrs = []) e args =
let e = Ast_builder.Default.pexp_apply ~loc e args in
{ e with pexp_attributes = attrs }
let value_binding ~loc ~pat ~expr ~attrs =
let vb = Ast_builder.Default.value_binding ~loc ~pat ~expr in
{ vb with pvb_attributes = attrs }
let value_description ~loc ~name ~type_ ~prim ~attrs =
let vd = Ast_builder.Default.value_description ~loc ~name ~type_ ~prim in
{ vd with pval_attributes = attrs }
end
module Jsx_runtime = struct
let elem name ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Elem"), name) }
let attr name ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), name) }
let null ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "null") }
let text ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "text") }
let int ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "int") }
let float ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "float") }
let fragment ~loc =
Builder.pexp_ident ~loc { loc; txt = Ldot (Lident "Jsx", "fragment") }
let syntax_option1 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option1") }
let syntax_option2 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option2") }
let syntax_option3 ~loc =
Builder.pexp_ident ~loc
{ loc; txt = Ldot (Ldot (Lident "Jsx", "Attr"), "option3") }
end
let child_to_elem child =
let loc = child.pexp_loc in
match child.pexp_desc with
" str " = = > " )
| Pexp_constant (Pconst_string _) ->
Builder.pexp_apply ~loc (Jsx_runtime.text ~loc) [ (Nolabel, child) ]
42 = = > Jsx.int(42 )
| Pexp_constant (Pconst_integer _) ->
Builder.pexp_apply ~loc (Jsx_runtime.int ~loc) [ (Nolabel, child) ]
3.14 = = > Jsx.float(3.14 )
| Pexp_constant (Pconst_float _) ->
Builder.pexp_apply ~loc (Jsx_runtime.float ~loc) [ (Nolabel, child) ]
| _ -> child
let process_children ~loc ~mapper l0 =
let rec loop l acc =
match l.pexp_desc with
| Pexp_construct ({ txt = Lident "[]"; _ }, None) -> (
match acc with
| [] -> `empty
| [ x ] -> `single (child_to_elem x)
| _ -> `array (Builder.pexp_array ~loc (List.rev_map child_to_elem acc)))
| Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple [ x; l' ]; _ })
-> loop l' (mapper#expression x :: acc)
| _not_a_list -> `single (mapper#expression l)
in
loop l0 []
let prop_to_apply ~loc:loc0 (arg_l, arg_e) =
match (arg_l, arg_e) with
? l:(val_1 , val_2 )
| ( Optional l
, { pexp_desc = Pexp_tuple [ val_1; val_2 ]
; pexp_loc = loc
; pexp_attributes
; pexp_loc_stack = _
} ) ->
let syn_fun = Jsx_runtime.syntax_option2 ~loc in
let syn_attr = Jsx_runtime.attr l ~loc in
Builder.pexp_apply ~loc:loc0 syn_fun ~attrs:pexp_attributes
[ (Nolabel, syn_attr); (Nolabel, val_1); (Nolabel, val_2) ]
? l:(val_1 , val_2 , val_3 )
| ( Optional l
, { pexp_desc = Pexp_tuple [ val_1; val_2; val_3 ]
; pexp_loc = loc
; pexp_attributes
; pexp_loc_stack = _
} ) ->
let syn_fun = Jsx_runtime.syntax_option3 ~loc in
let syn_attr = Jsx_runtime.attr l ~loc in
Builder.pexp_apply ~loc:loc0 syn_fun ~attrs:pexp_attributes
[ (Nolabel, syn_attr)
; (Nolabel, val_1)
; (Nolabel, val_2)
; (Nolabel, val_3)
]
? l :
| Optional l, val_1 ->
let syn_fun = Jsx_runtime.syntax_option1 ~loc:loc0 in
let syn_attr = Jsx_runtime.attr l ~loc:loc0 in
Builder.pexp_apply ~loc:loc0 syn_fun
[ (Nolabel, syn_attr); (Nolabel, val_1) ]
| Labelled l, _ ->
let attr_fun = Jsx_runtime.attr l ~loc:loc0 in
Builder.pexp_apply ~loc:loc0 attr_fun [ (Nolabel, arg_e) ]
| Nolabel, _ -> assert false
let prop_list_to_array ~loc (props : (arg_label * expression) list) =
let propsApplies = List.map (prop_to_apply ~loc) props in
Builder.pexp_array ~loc propsApplies
let extractChildren ?(removeLastPositionUnit = false) ~loc propsAndChildren =
let rec allButLast_ lst acc =
match lst with
| [] -> []
| [ ( Nolabel
, { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, None); _ } )
] -> acc
| (Nolabel, _) :: _rest ->
raise
(Invalid_argument
"JSX: found non-labelled argument before the last position")
| arg :: rest -> allButLast_ rest (arg :: acc)
[@@raises Invalid_argument]
in
let allButLast lst =
allButLast_ lst [] |> List.rev
[@@raises Invalid_argument]
in
match
List.partition
(fun (label, _) -> label = Labelled "children")
propsAndChildren
with
| [], props ->
( Builder.pexp_construct ~loc { loc; txt = Lident "[]" } None
, if removeLastPositionUnit then allButLast props else props )
| [ (_, childrenExpr) ], props ->
(childrenExpr, if removeLastPositionUnit then allButLast props else props)
| _ ->
raise
(Invalid_argument "JSX: somehow there's more than one `children` label")
[@@raises Invalid_argument]
let get_label = function
| Nolabel -> ""
| Labelled l | Optional l -> l
let rewritter =
let transformUppercaseCall3 ~caller modulePath mapper loc attrs _
callArguments =
let children, argsWithLabels =
extractChildren ~loc ~removeLastPositionUnit:true callArguments
in
let argsForMake = argsWithLabels in
let children' =
match process_children ~loc ~mapper children with
| `empty -> Ast_helper.Exp.construct (Loc.make ~loc (Lident "()")) None
| `single e -> e
| `array e -> e
in
let recursivelyTransformedArgsForMake =
argsForMake
|> List.map (fun (label, expression) ->
(label, mapper#expression expression))
in
let props = recursivelyTransformedArgsForMake in
let isCap str =
let first = String.sub str 0 1 [@@raises Invalid_argument] in
let capped = String.uppercase_ascii first in
first = capped
[@@raises Invalid_argument]
in
let ident =
match modulePath with
| Lident _ -> Ldot (modulePath, caller)
| Ldot (_modulePath, value) as fullPath when isCap value ->
Ldot (fullPath, caller)
| modulePath -> modulePath
in
Builder.pexp_apply ~loc ~attrs
(Builder.pexp_ident ~loc { txt = ident; loc })
(props @ [ (Nolabel, children') ])
[@@raises Invalid_argument]
in
let transformLowercaseCall3 mapper loc attrs callArguments id =
let children, nonChildrenProps =
extractChildren ~removeLastPositionUnit:true ~loc callArguments
in
match (id, children.pexp_desc) with
| ( "text"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.text ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
| ( "int"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.int ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
| ( "float"
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple l; _ }) ) ->
let elem_f = Jsx_runtime.float ~loc in
let arg =
match l with
| [ x; _nil_exp ] -> x
| _ ->
Location.raise_errorf ~loc "%s requires exactly one child node" id
in
let args = [ (Nolabel, arg) ] in
Builder.pexp_apply ~loc ~attrs elem_f args
| ( _
, Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple _; _ }) )
| _, Pexp_construct ({ txt = Lident "[]"; _ }, None) ->
let elem_f = Jsx_runtime.elem id ~loc in
let props =
nonChildrenProps
|> List.map (fun (label, e) -> (label, mapper#expression e))
|> prop_list_to_array ~loc
in
let children' =
match process_children ~loc ~mapper children with
| `empty -> Ast_helper.Exp.array ~loc []
| `single e -> Ast_helper.Exp.array ~loc [ e ]
| `array e -> e
in
let args =
[ |Jsx . ; bar| ]
(Nolabel, props)
(Nolabel, children')
]
in
Builder.pexp_apply ~loc ~attrs elem_f args
| _ ->
let elem_f = Jsx_runtime.elem id ~loc in
let props =
nonChildrenProps
|> List.map (fun (label, e) -> (label, mapper#expression e))
|> prop_list_to_array ~loc
in
let args =
[ |Jsx . ; bar| ]
(Nolabel, props)
(Nolabel, children)
]
in
Builder.pexp_apply ~loc ~attrs elem_f args
in
let transform_jsx_apply mapper f_exp f_args attrs =
match f_exp.pexp_desc with
| Pexp_ident caller -> (
match caller with
| { txt = Lident "createElement"; _ } ->
raise
(Invalid_argument
"JSX: `createElement` should be preceeded by a module name.")
Foo.createElement(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) )
| { loc; txt = Ldot (mod_path, ("createElement" | "make")) } ->
transformUppercaseCall3 ~caller:"make" mod_path mapper loc attrs f_exp
f_args
div(~prop1 = foo , ~prop2 = bar , ~children=[bla ] , ( ) )
| { loc; txt = Lident id } ->
transformLowercaseCall3 mapper loc attrs f_args id
Foo.bar(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) )
| { loc; txt = Ldot (mod_path, f_non_std) } ->
transformUppercaseCall3 ~caller:f_non_std mod_path mapper loc attrs
f_exp f_args
| { txt = Lapply _; _ } ->
raise
(Invalid_argument
"JSX: encountered a weird case while processing the code. Please \
report this!"))
| _ ->
raise
(Invalid_argument
"JSX: `createElement` should be preceeded by a simple, direct \
module name.")
[@@raises Invalid_argument]
in
object (mapper)
inherit Ast_traverse.map as super
method! expression exp =
match exp.pexp_desc with
| Pexp_apply (f_exp, f_args) -> (
let jsx_attrs, other_attrs =
List.partition
(fun attr -> attr.attr_name.txt = "JSX")
exp.pexp_attributes
in
match jsx_attrs with
| [] -> super#expression exp
| _ -> transform_jsx_apply mapper f_exp f_args other_attrs)
| Pexp_construct
({ txt = Lident "::"; loc; _ }, Some { pexp_desc = Pexp_tuple _; _ })
| Pexp_construct ({ txt = Lident "[]"; loc }, None) -> (
let jsx_attrs, other_attrs =
List.partition
(fun attr -> attr.attr_name.txt = "JSX")
exp.pexp_attributes
in
match jsx_attrs with
| [] -> super#expression exp
| _ ->
let children' =
match process_children ~loc ~mapper exp with
| `empty -> Ast_helper.Exp.array ~loc []
| `single e -> Ast_helper.Exp.array ~loc [ e ]
| `array e -> e
in
let args = [ (Nolabel, children') ] in
Builder.pexp_apply ~loc ~attrs:other_attrs
(Jsx_runtime.fragment ~loc)
args)
| _ -> super#expression exp
[@@raises Invalid_argument]
end
let () =
Driver.register_transformation "helix-ppx" ~impl:rewritter#structure
~intf:rewritter#signature
|
14b90923be10e27d5685213fbcdb7328f9acf4f0bbfea17c914f629b8df71e87 | dasuxullebt/uxul-world | game-object.lisp | Copyright 2009 - 2011
(in-package :uxul-world)
;; Define a class for the Standard Game-Object which has a draw-Method
;; which will be called at every frame, and a Collision-Box, and has a
unique ( x , y)-Coordinate with translations for both the
;; Object and the collision-box
We changed the api , and added stuff from Collision - Rectangle ( which
;; explains some documentation about it)
(defclass game-object (xy-coordinates)
((width :initarg :width
:initform 0
:accessor width
:type fixnum
:documentation "The width of that rectangle")
(height :initarg :height
:initform 0
:accessor height
:type fixnum
:documentation "The height of that rectangle")
(listen-to :initarg :listen-to
:initform NIL
:accessor listen-to
:documentation "List of rectangles and game-objects to
check for collisions at movement")
(colliding :initarg :colliding
:initform T
:accessor colliding
; :type boolean
:documentation "Throw Collisions with this
Collision-Rectangle to other Collision-Rectangles? (this
makes it a bit easier to \"turn off\" Objects, i.e. you
dont always have to remove them from the
listen-to-lists")
(visible :initarg :visible
:initform T
:accessor visible
; :type boolean
:documentation "Should this Object be drawn?")
(redraw :initarg :redraw
:initform T
:accessor redraw
:documentation "If set to nil, this object will be painted
once onto the Background of the Level and then never be
painted again (except when needed), i.e. the engine first
paints it onto its background-surface, and then it keeps
using its background-surface for all further images. This
makes drawing faster. It should be set to NIL whenever
possible, however, if the Object will change its place or
look different in the future, or should be painted over
some other object that can move or change its look, then it
must be set to T, because it must be redrawn. NOTICE: It is
not specified, what happens, if this Value changes during
runtime. It should not be set manually after it is used by
the engine.
**********************FIXME: DOESNT WORK ATM**********************
")
(active :initarg :active
:initform NIL
:accessor active
; :type boolean
:documentation "Will the Invoke-Function be called?")
(object-id :initarg :object-id
:initform NIL
:accessor object-id
:documentation "To identify an object, a room may give it an id."))
(:documentation "Define a Class for all Game-Objects. This class
has an invoke-, a draw- and an on-collide Function, which do
nothing per default." ))
(defmethod draw ((obj game-object))
"To be called when drawing the object - does nothing per default, except throwing a warning."
(format t "waring: draw-method not overridden. Object: ")
(write obj)
(sdl:push-quit-event))
(defmethod invoke ((obj game-object))
"To be called when invoking the object - does nothing per default, except throwing a warning."
(format t "warning: invoke-method not overridden. Object: ")
(write obj)
(sdl:push-quit-event))
(defmethod on-collision ((moving-object game-object) (standing-object game-object) (collision collision))
"To be called if a Collision occurs. May have more than one overriding declaration, to use the dispatcher."
(declare (ignore standing-object moving-object collision))
(format t "warning: on-collision-method not overridden."))
(defmethod half-width ((obj game-object))
(/ (width obj) 2))
(defmethod (setf half-width) (x (obj game-object))
(setf (width obj) (* x 2)))
(defmethod half-height ((obj game-object))
(/ (height obj) 2))
(defmethod (setf half-height) (x (obj game-object))
(setf (height obj) (* x 2)))
(defmethod mid-x ((obj game-object))
(+ (x obj) (half-width obj)))
(defmethod mid-y ((obj game-object))
(+ (y obj) (half-height obj)))
(defmethod (setf mid-x) (x (obj game-object))
(setf (x obj) (- x (half-width obj))))
(defmethod (setf mid-y) (y (obj game-object))
(setf (y obj) (- y (half-height obj))))
(defmethod move-about ((moving-rectangle game-object) (translation xy-struct))
(if (= (x translation) 0)
(when (not (= (y translation) 0))
(move-collision-rectangle-about-y moving-rectangle (y translation)))
(if (= (y translation) 0)
(move-collision-rectangle-about-x moving-rectangle (x translation))
(move-collision-rectangle-about-xy moving-rectangle (x translation) (y translation)))))
(defmethod move-to ((moving-rectangle game-object) (translation xy-struct))
"This is highly inefficient and should be replaced"
(move-about moving-rectangle
(make-xy (- (x translation) (x moving-rectangle)) (- (y translation) (y moving-rectangle)))))
(defmethod draw-bounds ((obj game-object))
"This function draws a rectangle with the Object's Bounds. May be useful for some debug-spam"
;; (sdl:draw-rectangle-* (+ (x obj) *current-translation-x*)
;; (+ (y obj) *current-translation-y*)
;; (width obj) (height obj)
;; :color sdl:*BLACK*)
)
(defun collide-blocks (moving-rectangle standing-rectangle collision)
"as MANY collision-methods need to move the moving-object around the
standing-object, we will write a function for doing that. IMPORTANT:
moving-rectangle MUST have a dont-ignore-property"
(declare (ignore standing-rectangle))
(directly-with-all-accessors collision collision
(setf (x moving-rectangle) (x pos))
(setf (y moving-rectangle) (y pos))
(cond
((or (eq direction :left) (eq direction :right))
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement))))))
((or (eq direction :up) (eq direction :down))
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0)))
(T ;; diagonal - argh! lets try to move up/down. if this fails,
;; lets try to move left/right. we're setting our
;; dont-ignore-flag to nil for that
(let ((current-y (y moving-rectangle))
(current-x (x moving-rectangle)))
(setf (dont-ignore moving-rectangle) nil)
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0))
(if (not (= current-x (x moving-rectangle)))
(progn
(setf (x moving-rectangle) current-x)
(setf (dont-ignore moving-rectangle) T)
;; now really move it!
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0)))
;else - it cannot move in x-direction...
(progn
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement)))))
(when (not (= current-y (y moving-rectangle)))
(setf (y moving-rectangle) current-y)
(setf (dont-ignore moving-rectangle) T)
;; now really move it!
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement)))))))))))))
| null | https://raw.githubusercontent.com/dasuxullebt/uxul-world/f05e44b099e5976411b3ef1f980ec616bd221425/game-object.lisp | lisp | Define a class for the Standard Game-Object which has a draw-Method
which will be called at every frame, and a Collision-Box, and has a
Object and the collision-box
explains some documentation about it)
:type boolean
:type boolean
:type boolean
(sdl:draw-rectangle-* (+ (x obj) *current-translation-x*)
(+ (y obj) *current-translation-y*)
(width obj) (height obj)
:color sdl:*BLACK*)
diagonal - argh! lets try to move up/down. if this fails,
lets try to move left/right. we're setting our
dont-ignore-flag to nil for that
now really move it!
else - it cannot move in x-direction...
now really move it! | Copyright 2009 - 2011
(in-package :uxul-world)
unique ( x , y)-Coordinate with translations for both the
We changed the api , and added stuff from Collision - Rectangle ( which
(defclass game-object (xy-coordinates)
((width :initarg :width
:initform 0
:accessor width
:type fixnum
:documentation "The width of that rectangle")
(height :initarg :height
:initform 0
:accessor height
:type fixnum
:documentation "The height of that rectangle")
(listen-to :initarg :listen-to
:initform NIL
:accessor listen-to
:documentation "List of rectangles and game-objects to
check for collisions at movement")
(colliding :initarg :colliding
:initform T
:accessor colliding
:documentation "Throw Collisions with this
Collision-Rectangle to other Collision-Rectangles? (this
makes it a bit easier to \"turn off\" Objects, i.e. you
dont always have to remove them from the
listen-to-lists")
(visible :initarg :visible
:initform T
:accessor visible
:documentation "Should this Object be drawn?")
(redraw :initarg :redraw
:initform T
:accessor redraw
:documentation "If set to nil, this object will be painted
once onto the Background of the Level and then never be
painted again (except when needed), i.e. the engine first
paints it onto its background-surface, and then it keeps
using its background-surface for all further images. This
makes drawing faster. It should be set to NIL whenever
possible, however, if the Object will change its place or
look different in the future, or should be painted over
some other object that can move or change its look, then it
must be set to T, because it must be redrawn. NOTICE: It is
not specified, what happens, if this Value changes during
runtime. It should not be set manually after it is used by
the engine.
**********************FIXME: DOESNT WORK ATM**********************
")
(active :initarg :active
:initform NIL
:accessor active
:documentation "Will the Invoke-Function be called?")
(object-id :initarg :object-id
:initform NIL
:accessor object-id
:documentation "To identify an object, a room may give it an id."))
(:documentation "Define a Class for all Game-Objects. This class
has an invoke-, a draw- and an on-collide Function, which do
nothing per default." ))
(defmethod draw ((obj game-object))
"To be called when drawing the object - does nothing per default, except throwing a warning."
(format t "waring: draw-method not overridden. Object: ")
(write obj)
(sdl:push-quit-event))
(defmethod invoke ((obj game-object))
"To be called when invoking the object - does nothing per default, except throwing a warning."
(format t "warning: invoke-method not overridden. Object: ")
(write obj)
(sdl:push-quit-event))
(defmethod on-collision ((moving-object game-object) (standing-object game-object) (collision collision))
"To be called if a Collision occurs. May have more than one overriding declaration, to use the dispatcher."
(declare (ignore standing-object moving-object collision))
(format t "warning: on-collision-method not overridden."))
(defmethod half-width ((obj game-object))
(/ (width obj) 2))
(defmethod (setf half-width) (x (obj game-object))
(setf (width obj) (* x 2)))
(defmethod half-height ((obj game-object))
(/ (height obj) 2))
(defmethod (setf half-height) (x (obj game-object))
(setf (height obj) (* x 2)))
(defmethod mid-x ((obj game-object))
(+ (x obj) (half-width obj)))
(defmethod mid-y ((obj game-object))
(+ (y obj) (half-height obj)))
(defmethod (setf mid-x) (x (obj game-object))
(setf (x obj) (- x (half-width obj))))
(defmethod (setf mid-y) (y (obj game-object))
(setf (y obj) (- y (half-height obj))))
(defmethod move-about ((moving-rectangle game-object) (translation xy-struct))
(if (= (x translation) 0)
(when (not (= (y translation) 0))
(move-collision-rectangle-about-y moving-rectangle (y translation)))
(if (= (y translation) 0)
(move-collision-rectangle-about-x moving-rectangle (x translation))
(move-collision-rectangle-about-xy moving-rectangle (x translation) (y translation)))))
(defmethod move-to ((moving-rectangle game-object) (translation xy-struct))
"This is highly inefficient and should be replaced"
(move-about moving-rectangle
(make-xy (- (x translation) (x moving-rectangle)) (- (y translation) (y moving-rectangle)))))
(defmethod draw-bounds ((obj game-object))
"This function draws a rectangle with the Object's Bounds. May be useful for some debug-spam"
)
(defun collide-blocks (moving-rectangle standing-rectangle collision)
"as MANY collision-methods need to move the moving-object around the
standing-object, we will write a function for doing that. IMPORTANT:
moving-rectangle MUST have a dont-ignore-property"
(declare (ignore standing-rectangle))
(directly-with-all-accessors collision collision
(setf (x moving-rectangle) (x pos))
(setf (y moving-rectangle) (y pos))
(cond
((or (eq direction :left) (eq direction :right))
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement))))))
((or (eq direction :up) (eq direction :down))
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0)))
(let ((current-y (y moving-rectangle))
(current-x (x moving-rectangle)))
(setf (dont-ignore moving-rectangle) nil)
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0))
(if (not (= current-x (x moving-rectangle)))
(progn
(setf (x moving-rectangle) current-x)
(setf (dont-ignore moving-rectangle) T)
(move-about moving-rectangle (make-xy (truncate (* (- 1 collision-time) (x desired-movement))) 0)))
(progn
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement)))))
(when (not (= current-y (y moving-rectangle)))
(setf (y moving-rectangle) current-y)
(setf (dont-ignore moving-rectangle) T)
(move-about moving-rectangle (make-xy 0 (truncate (* (- 1 collision-time) (y desired-movement)))))))))))))
|
0bba285c3a4c9329f14e613413177489576b4d547113fa979e0623c97d0d7f54 | escherize/bengine | app.cljs | (ns ^:figwheel-always bengine.app
(:require
[bengine.core :as core]
[cljs.nodejs :as node]
[mount.core :as mount]))
(enable-console-print!)
(mount/in-cljc-mode)
(cljs.nodejs/enable-util-print!)
(.on js/process "uncaughtException" #(js/console.error %))
(set! *main-cli-fn* core/main)
| null | https://raw.githubusercontent.com/escherize/bengine/ed9ae4adc31b47e9d4c330f03f697cc8bc74aa8e/env/dev/bengine/app.cljs | clojure | (ns ^:figwheel-always bengine.app
(:require
[bengine.core :as core]
[cljs.nodejs :as node]
[mount.core :as mount]))
(enable-console-print!)
(mount/in-cljc-mode)
(cljs.nodejs/enable-util-print!)
(.on js/process "uncaughtException" #(js/console.error %))
(set! *main-cli-fn* core/main)
| |
2da9b9d6741c4789c4bbb5c49b0c1c23ad873ee89096a6cece29b82435540c74 | linyinfeng/myml | Typing.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
module Myml.Typing
( NewVar (..),
TypingEnv,
Inference,
InferenceState (..),
MonadUnify,
MonadInference,
newVar,
runInference,
runInferenceT,
-- main infer function
infer,
-- instantiate and generalize
instantiate,
instantiateType,
instantiateRow,
instantiatePresence,
generalize,
replaceSafePresent,
-- unify
unifyProper,
unifyPresenceWithType,
unifyPresence,
unifyRow,
-- describe
describeScheme,
describeProper,
describePresence,
describeRow,
)
where
import Control.Monad.Except as Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Equivalence.Monad
import qualified Data.Equivalence.STT as STT
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
import Myml.Subst
import Myml.Syntax
import Prettyprinter
newtype NewVar = NewVar (Map.Map VarName Integer)
deriving (Show)
type TypingEnv = Map.Map VarName TypeScheme
type MonadUnify s m = MonadEquiv (STT.Class s TypeSubstituter TypeSubstituter) TypeSubstituter TypeSubstituter m
type MonadInference s m =
( MonadError Error m,
MonadUnify s m,
MonadReader TypingEnv m,
MonadState InferenceState m
)
type Inference s a = InferenceT s Identity a
type InferenceT s m a =
ExceptT
Error
( EquivT
s
TypeSubstituter
TypeSubstituter
( ReaderT
TypingEnv
(StateT InferenceState m)
)
)
a
data InferenceState = InferenceState
{ inferStateNewVar :: NewVar,
imperativeFeaturesEnabled :: Bool
}
deriving (Show)
runInference :: forall a. (forall s. Inference s a) -> TypingEnv -> InferenceState -> (Either Error a, InferenceState)
runInference inf env state = runIdentity (runInferenceT inf env state)
runInferenceT :: forall a m. (Monad m) => (forall s. InferenceT s m a) -> TypingEnv -> InferenceState -> m (Either Error a, InferenceState)
runInferenceT inf env = runStateT (runReaderT (runEquivT id (const id) (runExceptT inf)) env)
newVar :: MonadState InferenceState m => VarName -> m VarName
newVar prefix = do
NewVar m <- gets inferStateNewVar
let i = fromMaybe 0 (Map.lookup prefix m)
modify (\s -> s {inferStateNewVar = NewVar (Map.insert prefix (i + 1) m)})
return (if i == 0 then prefix else prefix ++ show i)
resetVarPrefix :: MonadState InferenceState m => Set.Set VarName -> m ()
resetVarPrefix ps = do
NewVar m <- gets inferStateNewVar
-- union = unionWith const
let m' = Map.map (const 0) (Map.restrictKeys m ps) `Map.union` m
modify (\s -> s {inferStateNewVar = NewVar m'})
newVarInner :: MonadState InferenceState m => Kind -> m VarName
newVarInner = newVar . ('_' :) . kindToPrefix
kindPrefixes :: Set.Set VarName
kindPrefixes = Set.fromList ["\x03b1", "\x03c6", "\x03c8", "\x03c1"]
kindToPrefix :: Kind -> VarName
kindToPrefix KProper = "\x03b1"
kindToPrefix KPresence = "\x03c6"
kindToPrefix KPresenceWithType = "\x03c8"
kindToPrefix KRow = "\x03c1"
kindToPrefix k = error ("Unknown kind for prefix" ++ show (pretty k))
checkImperativeFeaturesEnabled :: (MonadState InferenceState m, MonadError Error m) => Term -> m ()
checkImperativeFeaturesEnabled t = do
enabled <- gets imperativeFeaturesEnabled
unless enabled (throwError (ErrImperativeFeaturesDisabled t))
infer :: MonadInference s m => Term -> m Type
infer (TmVar x) =
reader (Map.lookup x) >>= \case
Nothing -> throwError (ErrUnboundedVariable x)
Just s -> instantiate s
infer (TmApp t1 t2) = do
ty1 <- infer t1
ty2 <- infer t2
nv <- TyVar <$> newVarInner KProper
unifyProper ty1 (TyArrow ty2 nv)
return nv
infer (TmAbs x t) = do
nv <- TyVar <$> newVarInner KProper
ty <- local (Map.insert x (ScmMono nv)) (infer t)
return (TyArrow nv ty)
infer (TmLet x t1 t2) = do
ty1 <- infer t1
ctx <- ask
ctx' <- mapM (describeScheme True Set.empty) ctx
local
(const ctx')
( do
s <- generalize t1 ty1
local (Map.insert x s) (infer t2)
)
infer TmEmptyRcd = return (TyRecord RowEmpty)
infer (TmRcdExtend l) =
instantiate
( ScmForall "a" KProper $
ScmForall "p" KPresence $
ScmForall "r" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( TyVar "a"
`TyArrow` TyRecord (RowPresence l (PresenceVar "p") (RowVar "r"))
`TyArrow` TyRecord
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "r")
)
)
)
infer (TmRcdUpdate l) =
instantiate
( ScmForall "a1" KProper $
ScmForall "a2" KProper $
ScmForall "r" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( TyVar "a1"
`TyArrow` TyRecord (RowPresence l (Present (TyVar "a2")) (RowVar "r"))
`TyArrow` TyRecord
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a1"))
(RowVar "r")
)
)
)
infer (TmRcdAccess l) =
instantiate
( ScmForall "a" KProper $
ScmForall "r" KRow $
ScmMono
( TyRecord (RowPresence l (Present (TyVar "a")) (RowVar "r"))
`TyArrow` TyVar "a"
)
)
infer TmEmptyMatch =
instantiate
(ScmForall "a" KProper $ ScmMono (TyVariant RowEmpty `TyArrow` TyVar "a"))
infer (TmMatchExtend l) =
instantiate
( ScmForall "a" KProper $
ScmForall "p" KPresence $
ScmForall "ret" KProper $
ScmForall "row" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( (TyVar "a" `TyArrow` TyVar "ret")
`TyArrow` ( TyVariant (RowPresence l (PresenceVar "p") (RowVar "row"))
`TyArrow` TyVar "ret"
)
`TyArrow` TyVariant
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "row")
)
`TyArrow` TyVar "ret"
)
)
infer (TmMatchUpdate l) =
instantiate
( ScmForall "a" KProper $
ScmForall "b" KProper $
ScmForall "ret" KProper $
ScmForall "row" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( (TyVar "a" `TyArrow` TyVar "ret")
`TyArrow` ( TyVariant
(RowPresence l (Present (TyVar "b")) (RowVar "row"))
`TyArrow` TyVar "ret"
)
`TyArrow` TyVariant
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "row")
)
`TyArrow` TyVar "ret"
)
)
infer (TmVariant l) =
instantiate
( ScmForall "a" KProper $
ScmForall "r" KRow $
ScmMono
( TyVar "a"
`TyArrow` TyVariant (RowPresence l (Present (TyVar "a")) (RowVar "r"))
)
)
infer TmRef = do
checkImperativeFeaturesEnabled TmRef
instantiate
(ScmForall "a" KProper (ScmMono (TyArrow (TyVar "a") (TyRef (TyVar "a")))))
infer TmDeref = do
checkImperativeFeaturesEnabled TmDeref
instantiate
(ScmForall "a" KProper (ScmMono (TyArrow (TyRef (TyVar "a")) (TyVar "a"))))
infer TmAssign = do
checkImperativeFeaturesEnabled TmAssign
instantiate
( ScmForall
"a"
KProper
(ScmMono (TyArrow (TyRef (TyVar "a")) (TyArrow (TyVar "a") TyUnit)))
)
infer (TmLoc _) = throwError ErrStoreTypingNotImplemented
infer (TmInteger _) = return TyInteger
infer TmIntegerPlus =
return (TyInteger `TyArrow` TyInteger `TyArrow` TyInteger)
infer TmIntegerMul = return (TyInteger `TyArrow` TyInteger `TyArrow` TyInteger)
infer TmIntegerAbs = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerSignum = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerNegate = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerQuotRem =
instantiate
( ScmForall "p1" KPresenceWithType $
ScmForall "p2" KPresenceWithType $
ScmMono
(TyInteger `TyArrow` TyInteger `TyArrow` typeQuotRem "p1" "p2")
)
infer TmIntegerCompare =
instantiate
( ScmForall "r" KRow $
ScmMono (TyInteger `TyArrow` TyInteger `TyArrow` typeOrdering "r")
)
infer (TmChar _) = return TyChar
infer TmIOGetChar =
instantiate
(ScmForall "r" KRow $ ScmMono (TyArrow TyUnit (typeMaybe TyChar "r")))
infer TmIOPutChar = return (TyArrow TyChar TyUnit)
infer TmCharCompare =
instantiate
( ScmForall "r" KRow $
ScmMono (TyChar `TyArrow` TyChar `TyArrow` typeOrdering "r")
)
instantiate :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypeScheme -> m Type
instantiate (ScmForall x KProper s) = do
nv <- newVarInner KProper
s' <- liftEither (substType (Map.singleton x (TySubProper (TyVar nv))) s)
instantiate s'
instantiate (ScmForall x KPresence s) = do
nv <- newVarInner KPresence
s' <-
liftEither
(substType (Map.singleton x (TySubPresence (PresenceVar nv))) s)
instantiate s'
instantiate (ScmForall x KPresenceWithType s) = do
nv <- newVarInner KPresenceWithType
s' <-
liftEither
( substType
(Map.singleton x (TySubPresenceWithType (PresenceWithTypeVar nv)))
s
)
instantiate s'
instantiate (ScmForall x KRow s) = do
nv <- newVarInner KRow
s' <- liftEither (substType (Map.singleton x (TySubRow (RowVar nv))) s)
instantiate s'
instantiate (ScmForall _ k _) = error ("Unknown kind: " ++ show (pretty k))
instantiate (ScmMono t) = instantiateType t
-- instantiate mu type in scheme
instantiateType :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => Type -> m Type
instantiateType (TyVar x) = return (TyVar x)
instantiateType (TyArrow t1 t2) =
TyArrow <$> instantiateType t1 <*> instantiateType t2
instantiateType (TyRecord r) = TyRecord <$> instantiateRow r
instantiateType (TyVariant r) = TyVariant <$> instantiateRow r
instantiateType (TyMu x t) = do
t' <- instantiateType t
unifyProper (TyVar x) t'
return (TyVar x)
instantiateType (TyRef t) = TyRef <$> instantiateType t
instantiateType TyInteger = return TyInteger
instantiateType TyChar = return TyChar
instantiateRow :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypeRow -> m TypeRow
instantiateRow RowEmpty = return RowEmpty
instantiateRow (RowVar x) = return (RowVar x)
instantiateRow (RowPresence l p r) =
RowPresence l <$> instantiatePresence p <*> instantiateRow r
instantiateRow (RowMu x r) = do
r' <- instantiateRow r
unifyRow (RowVar x) r'
return (RowVar x)
instantiatePresence :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypePresence -> m TypePresence
instantiatePresence Absent = return Absent
instantiatePresence (Present t) = Present <$> instantiateType t
instantiatePresence (PresenceVar x) = return (PresenceVar x)
instantiatePresence (PresenceVarWithType x t) =
PresenceVarWithType x <$> instantiateType t
generalize :: MonadInference s m => Term -> Type -> m TypeScheme
generalize t ty = do
tyDesc <- describeProper False Set.empty ty
-- this step replace all Presents only appear in covariant location to a fresh variable
tyRep <- replaceSafePresent tyDesc
tFv <- liftEither (fvType tyRep)
env <- ask
envFv <-
liftEither
( Map.foldl
(\a b -> bind2AndLift mapUnionWithKind a (fvScheme b))
(return Map.empty)
env
)
-- check kind conflicts
_ <- liftEither (mapUnionWithKind tFv envFv)
imperative <- gets imperativeFeaturesEnabled
let xs = tFv `Map.difference` envFv
xs' <-
if imperative && maybeExpansive t
then liftEither (dangerousVar tyRep >>= mapDiffWithKind xs)
else return xs
(sub, newXs) <- replacePrefix xs'
tyRep' <- liftEither (substType sub tyRep)
return (Map.foldrWithKey ScmForall (ScmMono tyRep') newXs)
where
bind2AndLift f ma mb = do
a <- ma
b <- mb
liftEither (f a b)
maybeExpansive :: Term -> Bool
maybeExpansive = not . isNonExpansive
isNonExpansive :: Term -> Bool
-- record extend and update
isNonExpansive (TmApp (TmApp (TmRcdExtend _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmApp (TmRcdUpdate _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmRcdAccess _) t) = isNonExpansive t
isNonExpansive TmEmptyRcd = True
-- match value
isNonExpansive (TmApp (TmApp (TmMatchExtend _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmApp (TmMatchUpdate _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive TmEmptyMatch = True
-- variant value
isNonExpansive (TmApp (TmVariant _) t) = isNonExpansive t
-- partial applied
isNonExpansive (TmApp (TmRcdExtend _) t) = isNonExpansive t
isNonExpansive (TmApp (TmRcdUpdate _) t) = isNonExpansive t
isNonExpansive (TmApp (TmMatchExtend _) t) = isNonExpansive t
isNonExpansive (TmApp (TmMatchUpdate _) t) = isNonExpansive t
isNonExpansive (TmApp TmAssign t) = isNonExpansive t
isNonExpansive (TmApp TmCharCompare t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerPlus t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerMul t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerQuotRem t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerCompare t) = isNonExpansive t
-- Basic
isNonExpansive (TmApp _ _) = False
isNonExpansive (TmVar _) = True
isNonExpansive (TmAbs _ _) = True
isNonExpansive (TmLet _ t1 t2) = isNonExpansive t1 && isNonExpansive t2
isNonExpansive _ = True
dangerousVar :: Type -> Either Error (Map.Map VarName Kind)
-- dangerousVar = fvType -- traditional value restriction
dangerousVar (TyVar _) = return Map.empty
dangerousVar (TyArrow t1 t2) = do
d1 <- fvType t1
d2 <- dangerousVar t2
mapUnionWithKind d1 d2
dangerousVar (TyRecord r) = dangerousVarRow r
dangerousVar (TyVariant r) = dangerousVarRow r
dangerousVar (TyMu x t) = do
dt <- dangerousVar t
case Map.lookup x dt of
Nothing -> return dt
Just KProper -> fvType (TyMu x t) -- x included in dangerous variables
Just k -> Left (ErrVarKindConflict x KProper k)
dangerousVar t = fvType t
dangerousVarRow :: TypeRow -> Either Error (Map.Map VarName Kind)
dangerousVarRow (RowPresence _label p r) = do
dp <- dangerousVarPresence p
dr <- dangerousVarRow r
mapUnionWithKind dp dr
dangerousVarRow (RowMu x r) = do
dr <- dangerousVarRow r
case Map.lookup x dr of
Nothing -> return dr
Just KRow -> fvRow (RowMu x r)
Just k -> Left (ErrVarKindConflict x KRow k)
dangerousVarRow (RowVar _) = return Map.empty -- for variant
dangerousVarRow RowEmpty = return Map.empty
dangerousVarPresence :: TypePresence -> Either Error (Map.Map VarName Kind)
dangerousVarPresence (Present t) = dangerousVar t
for record , mark generalization of PresenceVarWithType safe
dangerousVarPresence (PresenceVarWithType _ t) = dangerousVar t
dangerousVarPresence p = fvPresence p
replaceSafePresent :: (MonadError Error m, MonadState InferenceState m) => Type -> m Type
replaceSafePresent (TyArrow t1 t2) = TyArrow t1 <$> replaceSafePresent t2
replaceSafePresent (TyMu x t) = do
dt <- liftEither (dangerousVar t)
case Map.lookup x dt of
Nothing -> TyMu x <$> replaceSafePresent t
Just KProper -> return (TyMu x t) -- x included in dangerous variables
Just k -> throwError (ErrVarKindConflict x KProper k)
replaceSafePresent (TyRecord r) = TyRecord <$> replaceSafePresentRow True r
replaceSafePresent (TyVariant r) = TyVariant <$> replaceSafePresentRow False r
replaceSafePresent t = return t
replaceSafePresentRow :: (MonadError Error m, MonadState InferenceState m) => Bool -> TypeRow -> m TypeRow
replaceSafePresentRow shouldReplace (RowPresence label p r) =
RowPresence label
<$> replaceSafePresentPresence shouldReplace p
<*> replaceSafePresentRow shouldReplace r
replaceSafePresentRow shouldReplace (RowMu x r) = do
dr <- liftEither (dangerousVarRow r)
case Map.lookup x dr of
Nothing -> RowMu x <$> replaceSafePresentRow shouldReplace r
Just KRow -> return (RowMu x r) -- x included in dangerous variables
Just k -> throwError (ErrVarKindConflict x KRow k)
replaceSafePresentRow _shouldReplace r = return r
replaceSafePresentPresence :: (MonadError Error m, MonadState InferenceState m) => Bool -> TypePresence -> m TypePresence
replaceSafePresentPresence shouldReplace (Present t) =
if shouldReplace
then do
x <- newVarInner KPresenceWithType
PresenceVarWithType x <$> replaceSafePresent t
else Present <$> replaceSafePresent t
replaceSafePresentPresence _shouldReplace (PresenceVarWithType x t) =
PresenceVarWithType x <$> replaceSafePresent t
replaceSafePresentPresence _shouldReplace p = return p
replacePrefix ::
(MonadState InferenceState m, MonadError Error m) =>
Map.Map VarName Kind ->
m (Map.Map VarName TypeSubstituter, Map.Map VarName Kind)
replacePrefix m = do
resetVarPrefix kindPrefixes
nameMap <- sequence (Map.map (newVar . kindToPrefix) m)
let inv = Map.fromList [(v, k) | (k, v) <- Map.toList nameMap]
kindMap = Map.map (m Map.!) inv
substMap <- liftEither (sequence (Map.intersectionWith varToTySub m nameMap))
return (substMap, kindMap)
ensureProper :: (MonadError Error m) => TypeSubstituter -> m Type
ensureProper (TySubProper t) = return t
ensureProper s = throwError (ErrUnifyKindMismatch KProper (kindOfTySub s))
ensurePresence :: (MonadError Error m) => TypeSubstituter -> m TypePresence
ensurePresence (TySubPresence p) = return p
ensurePresence s = throwError (ErrUnifyKindMismatch KPresence (kindOfTySub s))
ensurePresenceWithType ::
(MonadError Error m) => TypeSubstituter -> m PresenceWithType
ensurePresenceWithType (TySubPresenceWithType p) = return p
ensurePresenceWithType s =
throwError (ErrUnifyKindMismatch KPresenceWithType (kindOfTySub s))
ensureRow :: (MonadError Error m) => TypeSubstituter -> m TypeRow
ensureRow (TySubRow r) = return r
ensureRow s = throwError (ErrUnifyKindMismatch KRow (kindOfTySub s))
unifyProper :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => MonadUnify s m => Type -> Type -> m ()
unifyProper t1 t2 = do
t1' <- classDesc (TySubProper t1) >>= ensureProper
t2' <- classDesc (TySubProper t2) >>= ensureProper
if t1' == t2'
then return ()
else case (t1', t2') of
(TyVar x1, _) -> equate (TySubProper (TyVar x1)) (TySubProper t2')
(_, TyVar x2) -> equate (TySubProper (TyVar x2)) (TySubProper t1')
_ -> do
-- record t1' already unified with t2'
equate (TySubProper t1') (TySubProper t2')
unifyProper' t1' t2' -- unify structures
unifyProper' :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => Type -> Type -> m ()
unifyProper' (TyArrow t11 t12) (TyArrow t21 t22) =
unifyProper t11 t21 >> unifyProper t12 t22
unifyProper' (TyRecord r1) (TyRecord r2) = unifyRow r1 r2
unifyProper' (TyVariant r1) (TyVariant r2) = unifyRow r1 r2
unifyProper' (TyRef t1) (TyRef t2) = unifyProper t1 t2
unifyProper' t1 t2 =
throwError (ErrUnifyNoRuleApplied (TySubProper t1) (TySubProper t2))
unifyPresenceWithType :: (MonadError Error m, MonadUnify s m) => PresenceWithType -> PresenceWithType -> m ()
unifyPresenceWithType p1 p2 = do
p1' <- classDesc (TySubPresenceWithType p1) >>= ensurePresenceWithType
p2' <- classDesc (TySubPresenceWithType p2) >>= ensurePresenceWithType
if p1' == p2'
then return ()
else case (p1', p2') of
(PresenceWithTypeVar x1, _) ->
equate
(TySubPresenceWithType (PresenceWithTypeVar x1))
(TySubPresenceWithType p2')
(_, PresenceWithTypeVar x2) ->
equate
(TySubPresenceWithType (PresenceWithTypeVar x2))
(TySubPresenceWithType p1')
_ ->
throwError
( ErrUnifyNoRuleApplied
(TySubPresenceWithType p1')
(TySubPresenceWithType p2')
)
unifyPresence :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypePresence -> TypePresence -> m ()
unifyPresence p1 p2 = do
p1' <- classDesc (TySubPresence p1) >>= ensurePresence
p2' <- classDesc (TySubPresence p2) >>= ensurePresence
if p1' == p2'
then return ()
else case (p1', p2') of
(PresenceVar x1, _) ->
equate (TySubPresence (PresenceVar x1)) (TySubPresence p2')
(_, PresenceVar x2) ->
equate (TySubPresence (PresenceVar x2)) (TySubPresence p1')
_ -> unifyPresence' p1' p2'
unifyPresence' :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypePresence -> TypePresence -> m ()
unifyPresence' (Present t1) (Present t2) = unifyProper t1 t2
unifyPresence' (PresenceVarWithType x1 _) Absent =
unifyPresenceWithType (PresenceWithTypeVar x1) PresenceWithTypeAbsent
unifyPresence' (PresenceVarWithType x1 t1) (Present t2) =
unifyPresenceWithType (PresenceWithTypeVar x1) PresenceWithTypePresent
>> unifyProper t1 t2
unifyPresence' (PresenceVarWithType x1 t1) (PresenceVarWithType x2 t2) =
unifyPresenceWithType (PresenceWithTypeVar x1) (PresenceWithTypeVar x2)
>> unifyProper t1 t2
unifyPresence' Absent (PresenceVarWithType x2 _) =
unifyPresenceWithType (PresenceWithTypeVar x2) PresenceWithTypeAbsent
unifyPresence' (Present t1) (PresenceVarWithType x2 t2) =
unifyPresenceWithType (PresenceWithTypeVar x2) PresenceWithTypePresent
>> unifyProper t1 t2
unifyPresence' p1 p2 =
throwError (ErrUnifyNoRuleApplied (TySubPresence p1) (TySubPresence p2))
unifyRow :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypeRow -> TypeRow -> m ()
unifyRow r1 r2 = do
r1' <- classDesc (TySubRow r1) >>= ensureRow
r2' <- classDesc (TySubRow r2) >>= ensureRow
if r1' == r2'
then return ()
else case (r1', r2') of
(RowVar x1, _) -> equate (TySubRow (RowVar x1)) (TySubRow r2')
(_, RowVar x2) -> equate (TySubRow (RowVar x2)) (TySubRow r1')
-- _ -> unifyRow' r1' r2'
_ -> do
-- record r1' already unified with r2'
-- equate (TySubRow r1') (TySubRow r2')
unifyRow' r1' r2' -- unify structures
unifyRow' :: (MonadError Error m, MonadState InferenceState m, MonadUnify s m) => TypeRow -> TypeRow -> m ()
unifyRow' RowEmpty (RowPresence _l p r) =
unifyPresence p Absent >> unifyRow r RowEmpty
unifyRow' (RowPresence _l p r) RowEmpty =
unifyPresence p Absent >> unifyRow r RowEmpty
unifyRow' (RowPresence l1 p1 r1) (RowPresence l2 p2 r2) =
if l1 == l2
then unifyPresence p1 p2 >> unifyRow r1 r2
else do
r3 <- newVarInner KRow
let r3' = RowVar r3
unifyRow r1 (RowPresence l2 p2 r3')
unifyRow r2 (RowPresence l1 p1 r3')
unifyRow' r1 r2 =
throwError (ErrUnifyNoRuleApplied (TySubRow r1) (TySubRow r2))
-- add kind check
describeScheme :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypeScheme -> m TypeScheme
describeScheme allowMu ctx (ScmForall x k s) =
ScmForall x k <$> describeScheme allowMu (Set.insert x ctx) s
describeScheme allowMu ctx (ScmMono t) =
ScmMono <$> describeProper allowMu ctx t
describeProper :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> Type -> m Type
describeProper _ ctx (TyVar x) | x `Set.member` ctx = return (TyVar x)
describeProper allowMu ctx (TyVar x) = do
t <- classDesc (TySubProper (TyVar x)) >>= ensureProper
if t == TyVar x
then return (TyVar x)
else do
t' <- describeProper allowMu (Set.insert x ctx) t
fv <- liftEither (fvType t')
case Map.lookup x fv of
Nothing -> return t'
Just KProper -> return (TyMu x t')
Just k -> throwError (ErrVarKindConflict x KProper k)
describeProper allowMu ctx (TyArrow t1 t2) =
TyArrow <$> describeProper allowMu ctx t1 <*> describeProper allowMu ctx t2
describeProper allowMu ctx (TyRecord row) =
TyRecord <$> describeRow allowMu ctx row
describeProper allowMu ctx (TyVariant row) =
TyVariant <$> describeRow allowMu ctx row
describeProper allowMu ctx (TyRef t) = TyRef <$> describeProper allowMu ctx t
describeProper allowMu ctx (TyMu x t) =
if allowMu
then TyMu x <$> describeProper allowMu (Set.insert x ctx) t
else throwError (ErrCanNotHandleMuType (TyMu x t))
describeProper _ _ TyInteger = return TyInteger
describeProper _ _ TyChar = return TyChar
describePresence ::
(MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypePresence -> m TypePresence
describePresence _ _ Absent = return Absent
describePresence allowMu ctx (Present t) =
Present <$> describeProper allowMu ctx t
describePresence allowMu ctx (PresenceVar x) = do
p <- classDesc (TySubPresence (PresenceVar x)) >>= ensurePresence
if p == PresenceVar x
then return (PresenceVar x)
else describePresence allowMu ctx p
describePresence allowMu ctx (PresenceVarWithType x t) = do
pt <- describePresenceWithType allowMu ctx (PresenceWithTypeVar x)
case pt of
PresenceWithTypeAbsent -> return Absent
PresenceWithTypePresent -> Present <$> describeProper allowMu ctx t
PresenceWithTypeVar x' ->
PresenceVarWithType x' <$> describeProper allowMu ctx t
describePresenceWithType :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> PresenceWithType -> m PresenceWithType
describePresenceWithType _ _ PresenceWithTypeAbsent =
return PresenceWithTypeAbsent
describePresenceWithType _ _ PresenceWithTypePresent =
return PresenceWithTypePresent
describePresenceWithType allowMu ctx (PresenceWithTypeVar x) = do
pt <-
classDesc (TySubPresenceWithType (PresenceWithTypeVar x))
>>= ensurePresenceWithType
if pt == PresenceWithTypeVar x
then return (PresenceWithTypeVar x)
else describePresenceWithType allowMu ctx pt
describeRow :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypeRow -> m TypeRow
describeRow _ _ RowEmpty = return RowEmpty
describeRow _ ctx (RowVar x) | x `Set.member` ctx = return (RowVar x)
describeRow allowMu ctx (RowVar x) = do
r <- classDesc (TySubRow (RowVar x)) >>= ensureRow
if r == RowVar x
then return (RowVar x)
else do
r' <- describeRow allowMu (Set.insert x ctx) r
fv <- liftEither (fvRow r')
case Map.lookup x fv of
Nothing -> return r'
Just KRow -> return (RowMu x r')
Just k -> throwError (ErrVarKindConflict x KRow k)
describeRow allowMu ctx (RowPresence l p r) =
RowPresence l <$> describePresence allowMu ctx p <*> describeRow allowMu ctx r
describeRow allowMu ctx (RowMu x r) =
if allowMu
then RowMu x <$> describeRow allowMu (Set.insert x ctx) r
else throwError (ErrCanNotHandleMuRow (RowMu x r))
-- regTreeEq' :: Type -> Type -> Bool
regTreeEq ' t1 t2 = case ( runMaybeT ( regTreeEq t1 t2 ) ) Set.empty of
-- (Nothing, _) -> False
-- (Just (), _) -> True
-- regTreeNeq' :: Type -> Type -> Bool
-- regTreeNeq' t1 t2 = not (regTreeEq' t1 t2)
-- regTreeEq
-- :: (Monad m) => Type -> Type -> MaybeT (StateT (Set.Set (Type, Type)) m) ()
regTreeEq t1 t2 = gets ( Set.member ( t1 , t2 ) ) > > = \case
-- True -> return ()
-- False -> modify (Set.insert (t1, t2)) >> case (t1, t2) of
-- (TyBool, TyBool) -> return ()
( TyNat , TyNat ) - > return ( )
( TyArrow t11 t12 , TyArrow t21 t22 ) - >
regTreeEq t11 t21 > > regTreeEq t12 t22
( TyRef t1 ' , TyRef t2 ' ) - > regTreeEq t1 ' t2 '
( TyRecord r1 , TyRecord r2 ) - > regTreeEqRow r1 r2
-- (TyVariant r1 , TyVariant r2) -> regTreeEqRow r1 r2
( TyVar x1 , TyVar x2 ) | x1 = = x2 - > return ( )
-- (TyMu x1 t12, _) ->
regTreeEq ( applySubst ( Map.singleton x1 ( TySubProper t1 ) ) t12 ) t2
( _ , ) - >
regTreeEq t1 ( applySubst ( Map.singleton x2 ( TySubProper t2 ) ) t22 )
-- _ -> mzero
-- regTreeEqRow
-- :: (Monad m)
= >
-- -> TypeRow
-- -> MaybeT (StateT (Set.Set (Type, Type)) m) ()
-- regTreeEqRow (TyRow f1 cof1) (TyRow f2 cof2)
-- | Map.keysSet f1 == Map.keysSet f2
= sequence _ ( Map.intersectionWith regTreeEqPresence )
> > case ( cof1 , ) of
-- (CofAllAbsent, CofAllAbsent) -> return ()
-- (CofRowVar x1, CofRowVar x2) | x1 == x2 -> return ()
-- _ -> mzero
-- | otherwise
-- = mzero
-- regTreeEqPresence
-- :: (Monad m)
-- => TypePresence
-- -> TypePresence
-- -> MaybeT (StateT (Set.Set (Type, Type)) m) ()
-- regTreeEqPresence p1 p2 = case (p1, p2) of
-- (Absent , Absent ) -> return ()
-- (Present t1, Present t2) -> regTreeEq t1 t2
-- (PresenceVar x1, PresenceVar x2) | x1 == x2 -> return ()
-- (PresenceVarWithType x1 t1, PresenceVarWithType x2 t2) | x1 == x2 ->
-- regTreeEq t1 t2
-- _ -> mzero
| null | https://raw.githubusercontent.com/linyinfeng/myml/1220a1474784eebce9ff95f46a3ff0a5f756e9a7/src/Myml/Typing.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
main infer function
instantiate and generalize
unify
describe
union = unionWith const
instantiate mu type in scheme
this step replace all Presents only appear in covariant location to a fresh variable
check kind conflicts
record extend and update
match value
variant value
partial applied
Basic
dangerousVar = fvType -- traditional value restriction
x included in dangerous variables
for variant
x included in dangerous variables
x included in dangerous variables
record t1' already unified with t2'
unify structures
_ -> unifyRow' r1' r2'
record r1' already unified with r2'
equate (TySubRow r1') (TySubRow r2')
unify structures
add kind check
regTreeEq' :: Type -> Type -> Bool
(Nothing, _) -> False
(Just (), _) -> True
regTreeNeq' :: Type -> Type -> Bool
regTreeNeq' t1 t2 = not (regTreeEq' t1 t2)
regTreeEq
:: (Monad m) => Type -> Type -> MaybeT (StateT (Set.Set (Type, Type)) m) ()
True -> return ()
False -> modify (Set.insert (t1, t2)) >> case (t1, t2) of
(TyBool, TyBool) -> return ()
(TyVariant r1 , TyVariant r2) -> regTreeEqRow r1 r2
(TyMu x1 t12, _) ->
_ -> mzero
regTreeEqRow
:: (Monad m)
-> TypeRow
-> MaybeT (StateT (Set.Set (Type, Type)) m) ()
regTreeEqRow (TyRow f1 cof1) (TyRow f2 cof2)
| Map.keysSet f1 == Map.keysSet f2
(CofAllAbsent, CofAllAbsent) -> return ()
(CofRowVar x1, CofRowVar x2) | x1 == x2 -> return ()
_ -> mzero
| otherwise
= mzero
regTreeEqPresence
:: (Monad m)
=> TypePresence
-> TypePresence
-> MaybeT (StateT (Set.Set (Type, Type)) m) ()
regTreeEqPresence p1 p2 = case (p1, p2) of
(Absent , Absent ) -> return ()
(Present t1, Present t2) -> regTreeEq t1 t2
(PresenceVar x1, PresenceVar x2) | x1 == x2 -> return ()
(PresenceVarWithType x1 t1, PresenceVarWithType x2 t2) | x1 == x2 ->
regTreeEq t1 t2
_ -> mzero | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
module Myml.Typing
( NewVar (..),
TypingEnv,
Inference,
InferenceState (..),
MonadUnify,
MonadInference,
newVar,
runInference,
runInferenceT,
infer,
instantiate,
instantiateType,
instantiateRow,
instantiatePresence,
generalize,
replaceSafePresent,
unifyProper,
unifyPresenceWithType,
unifyPresence,
unifyRow,
describeScheme,
describeProper,
describePresence,
describeRow,
)
where
import Control.Monad.Except as Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Equivalence.Monad
import qualified Data.Equivalence.STT as STT
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
import Myml.Subst
import Myml.Syntax
import Prettyprinter
newtype NewVar = NewVar (Map.Map VarName Integer)
deriving (Show)
type TypingEnv = Map.Map VarName TypeScheme
type MonadUnify s m = MonadEquiv (STT.Class s TypeSubstituter TypeSubstituter) TypeSubstituter TypeSubstituter m
type MonadInference s m =
( MonadError Error m,
MonadUnify s m,
MonadReader TypingEnv m,
MonadState InferenceState m
)
type Inference s a = InferenceT s Identity a
type InferenceT s m a =
ExceptT
Error
( EquivT
s
TypeSubstituter
TypeSubstituter
( ReaderT
TypingEnv
(StateT InferenceState m)
)
)
a
data InferenceState = InferenceState
{ inferStateNewVar :: NewVar,
imperativeFeaturesEnabled :: Bool
}
deriving (Show)
runInference :: forall a. (forall s. Inference s a) -> TypingEnv -> InferenceState -> (Either Error a, InferenceState)
runInference inf env state = runIdentity (runInferenceT inf env state)
runInferenceT :: forall a m. (Monad m) => (forall s. InferenceT s m a) -> TypingEnv -> InferenceState -> m (Either Error a, InferenceState)
runInferenceT inf env = runStateT (runReaderT (runEquivT id (const id) (runExceptT inf)) env)
newVar :: MonadState InferenceState m => VarName -> m VarName
newVar prefix = do
NewVar m <- gets inferStateNewVar
let i = fromMaybe 0 (Map.lookup prefix m)
modify (\s -> s {inferStateNewVar = NewVar (Map.insert prefix (i + 1) m)})
return (if i == 0 then prefix else prefix ++ show i)
resetVarPrefix :: MonadState InferenceState m => Set.Set VarName -> m ()
resetVarPrefix ps = do
NewVar m <- gets inferStateNewVar
let m' = Map.map (const 0) (Map.restrictKeys m ps) `Map.union` m
modify (\s -> s {inferStateNewVar = NewVar m'})
newVarInner :: MonadState InferenceState m => Kind -> m VarName
newVarInner = newVar . ('_' :) . kindToPrefix
kindPrefixes :: Set.Set VarName
kindPrefixes = Set.fromList ["\x03b1", "\x03c6", "\x03c8", "\x03c1"]
kindToPrefix :: Kind -> VarName
kindToPrefix KProper = "\x03b1"
kindToPrefix KPresence = "\x03c6"
kindToPrefix KPresenceWithType = "\x03c8"
kindToPrefix KRow = "\x03c1"
kindToPrefix k = error ("Unknown kind for prefix" ++ show (pretty k))
checkImperativeFeaturesEnabled :: (MonadState InferenceState m, MonadError Error m) => Term -> m ()
checkImperativeFeaturesEnabled t = do
enabled <- gets imperativeFeaturesEnabled
unless enabled (throwError (ErrImperativeFeaturesDisabled t))
infer :: MonadInference s m => Term -> m Type
infer (TmVar x) =
reader (Map.lookup x) >>= \case
Nothing -> throwError (ErrUnboundedVariable x)
Just s -> instantiate s
infer (TmApp t1 t2) = do
ty1 <- infer t1
ty2 <- infer t2
nv <- TyVar <$> newVarInner KProper
unifyProper ty1 (TyArrow ty2 nv)
return nv
infer (TmAbs x t) = do
nv <- TyVar <$> newVarInner KProper
ty <- local (Map.insert x (ScmMono nv)) (infer t)
return (TyArrow nv ty)
infer (TmLet x t1 t2) = do
ty1 <- infer t1
ctx <- ask
ctx' <- mapM (describeScheme True Set.empty) ctx
local
(const ctx')
( do
s <- generalize t1 ty1
local (Map.insert x s) (infer t2)
)
infer TmEmptyRcd = return (TyRecord RowEmpty)
infer (TmRcdExtend l) =
instantiate
( ScmForall "a" KProper $
ScmForall "p" KPresence $
ScmForall "r" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( TyVar "a"
`TyArrow` TyRecord (RowPresence l (PresenceVar "p") (RowVar "r"))
`TyArrow` TyRecord
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "r")
)
)
)
infer (TmRcdUpdate l) =
instantiate
( ScmForall "a1" KProper $
ScmForall "a2" KProper $
ScmForall "r" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( TyVar "a1"
`TyArrow` TyRecord (RowPresence l (Present (TyVar "a2")) (RowVar "r"))
`TyArrow` TyRecord
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a1"))
(RowVar "r")
)
)
)
infer (TmRcdAccess l) =
instantiate
( ScmForall "a" KProper $
ScmForall "r" KRow $
ScmMono
( TyRecord (RowPresence l (Present (TyVar "a")) (RowVar "r"))
`TyArrow` TyVar "a"
)
)
infer TmEmptyMatch =
instantiate
(ScmForall "a" KProper $ ScmMono (TyVariant RowEmpty `TyArrow` TyVar "a"))
infer (TmMatchExtend l) =
instantiate
( ScmForall "a" KProper $
ScmForall "p" KPresence $
ScmForall "ret" KProper $
ScmForall "row" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( (TyVar "a" `TyArrow` TyVar "ret")
`TyArrow` ( TyVariant (RowPresence l (PresenceVar "p") (RowVar "row"))
`TyArrow` TyVar "ret"
)
`TyArrow` TyVariant
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "row")
)
`TyArrow` TyVar "ret"
)
)
infer (TmMatchUpdate l) =
instantiate
( ScmForall "a" KProper $
ScmForall "b" KProper $
ScmForall "ret" KProper $
ScmForall "row" KRow $
ScmForall "pt" KPresenceWithType $
ScmMono
( (TyVar "a" `TyArrow` TyVar "ret")
`TyArrow` ( TyVariant
(RowPresence l (Present (TyVar "b")) (RowVar "row"))
`TyArrow` TyVar "ret"
)
`TyArrow` TyVariant
( RowPresence
l
(PresenceVarWithType "pt" (TyVar "a"))
(RowVar "row")
)
`TyArrow` TyVar "ret"
)
)
infer (TmVariant l) =
instantiate
( ScmForall "a" KProper $
ScmForall "r" KRow $
ScmMono
( TyVar "a"
`TyArrow` TyVariant (RowPresence l (Present (TyVar "a")) (RowVar "r"))
)
)
infer TmRef = do
checkImperativeFeaturesEnabled TmRef
instantiate
(ScmForall "a" KProper (ScmMono (TyArrow (TyVar "a") (TyRef (TyVar "a")))))
infer TmDeref = do
checkImperativeFeaturesEnabled TmDeref
instantiate
(ScmForall "a" KProper (ScmMono (TyArrow (TyRef (TyVar "a")) (TyVar "a"))))
infer TmAssign = do
checkImperativeFeaturesEnabled TmAssign
instantiate
( ScmForall
"a"
KProper
(ScmMono (TyArrow (TyRef (TyVar "a")) (TyArrow (TyVar "a") TyUnit)))
)
infer (TmLoc _) = throwError ErrStoreTypingNotImplemented
infer (TmInteger _) = return TyInteger
infer TmIntegerPlus =
return (TyInteger `TyArrow` TyInteger `TyArrow` TyInteger)
infer TmIntegerMul = return (TyInteger `TyArrow` TyInteger `TyArrow` TyInteger)
infer TmIntegerAbs = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerSignum = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerNegate = return (TyInteger `TyArrow` TyInteger)
infer TmIntegerQuotRem =
instantiate
( ScmForall "p1" KPresenceWithType $
ScmForall "p2" KPresenceWithType $
ScmMono
(TyInteger `TyArrow` TyInteger `TyArrow` typeQuotRem "p1" "p2")
)
infer TmIntegerCompare =
instantiate
( ScmForall "r" KRow $
ScmMono (TyInteger `TyArrow` TyInteger `TyArrow` typeOrdering "r")
)
infer (TmChar _) = return TyChar
infer TmIOGetChar =
instantiate
(ScmForall "r" KRow $ ScmMono (TyArrow TyUnit (typeMaybe TyChar "r")))
infer TmIOPutChar = return (TyArrow TyChar TyUnit)
infer TmCharCompare =
instantiate
( ScmForall "r" KRow $
ScmMono (TyChar `TyArrow` TyChar `TyArrow` typeOrdering "r")
)
instantiate :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypeScheme -> m Type
instantiate (ScmForall x KProper s) = do
nv <- newVarInner KProper
s' <- liftEither (substType (Map.singleton x (TySubProper (TyVar nv))) s)
instantiate s'
instantiate (ScmForall x KPresence s) = do
nv <- newVarInner KPresence
s' <-
liftEither
(substType (Map.singleton x (TySubPresence (PresenceVar nv))) s)
instantiate s'
instantiate (ScmForall x KPresenceWithType s) = do
nv <- newVarInner KPresenceWithType
s' <-
liftEither
( substType
(Map.singleton x (TySubPresenceWithType (PresenceWithTypeVar nv)))
s
)
instantiate s'
instantiate (ScmForall x KRow s) = do
nv <- newVarInner KRow
s' <- liftEither (substType (Map.singleton x (TySubRow (RowVar nv))) s)
instantiate s'
instantiate (ScmForall _ k _) = error ("Unknown kind: " ++ show (pretty k))
instantiate (ScmMono t) = instantiateType t
instantiateType :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => Type -> m Type
instantiateType (TyVar x) = return (TyVar x)
instantiateType (TyArrow t1 t2) =
TyArrow <$> instantiateType t1 <*> instantiateType t2
instantiateType (TyRecord r) = TyRecord <$> instantiateRow r
instantiateType (TyVariant r) = TyVariant <$> instantiateRow r
instantiateType (TyMu x t) = do
t' <- instantiateType t
unifyProper (TyVar x) t'
return (TyVar x)
instantiateType (TyRef t) = TyRef <$> instantiateType t
instantiateType TyInteger = return TyInteger
instantiateType TyChar = return TyChar
instantiateRow :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypeRow -> m TypeRow
instantiateRow RowEmpty = return RowEmpty
instantiateRow (RowVar x) = return (RowVar x)
instantiateRow (RowPresence l p r) =
RowPresence l <$> instantiatePresence p <*> instantiateRow r
instantiateRow (RowMu x r) = do
r' <- instantiateRow r
unifyRow (RowVar x) r'
return (RowVar x)
instantiatePresence :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => TypePresence -> m TypePresence
instantiatePresence Absent = return Absent
instantiatePresence (Present t) = Present <$> instantiateType t
instantiatePresence (PresenceVar x) = return (PresenceVar x)
instantiatePresence (PresenceVarWithType x t) =
PresenceVarWithType x <$> instantiateType t
generalize :: MonadInference s m => Term -> Type -> m TypeScheme
generalize t ty = do
tyDesc <- describeProper False Set.empty ty
tyRep <- replaceSafePresent tyDesc
tFv <- liftEither (fvType tyRep)
env <- ask
envFv <-
liftEither
( Map.foldl
(\a b -> bind2AndLift mapUnionWithKind a (fvScheme b))
(return Map.empty)
env
)
_ <- liftEither (mapUnionWithKind tFv envFv)
imperative <- gets imperativeFeaturesEnabled
let xs = tFv `Map.difference` envFv
xs' <-
if imperative && maybeExpansive t
then liftEither (dangerousVar tyRep >>= mapDiffWithKind xs)
else return xs
(sub, newXs) <- replacePrefix xs'
tyRep' <- liftEither (substType sub tyRep)
return (Map.foldrWithKey ScmForall (ScmMono tyRep') newXs)
where
bind2AndLift f ma mb = do
a <- ma
b <- mb
liftEither (f a b)
maybeExpansive :: Term -> Bool
maybeExpansive = not . isNonExpansive
isNonExpansive :: Term -> Bool
isNonExpansive (TmApp (TmApp (TmRcdExtend _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmApp (TmRcdUpdate _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmRcdAccess _) t) = isNonExpansive t
isNonExpansive TmEmptyRcd = True
isNonExpansive (TmApp (TmApp (TmMatchExtend _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive (TmApp (TmApp (TmMatchUpdate _) t1) t2) =
isNonExpansive t1 && isNonExpansive t2
isNonExpansive TmEmptyMatch = True
isNonExpansive (TmApp (TmVariant _) t) = isNonExpansive t
isNonExpansive (TmApp (TmRcdExtend _) t) = isNonExpansive t
isNonExpansive (TmApp (TmRcdUpdate _) t) = isNonExpansive t
isNonExpansive (TmApp (TmMatchExtend _) t) = isNonExpansive t
isNonExpansive (TmApp (TmMatchUpdate _) t) = isNonExpansive t
isNonExpansive (TmApp TmAssign t) = isNonExpansive t
isNonExpansive (TmApp TmCharCompare t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerPlus t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerMul t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerQuotRem t) = isNonExpansive t
isNonExpansive (TmApp TmIntegerCompare t) = isNonExpansive t
isNonExpansive (TmApp _ _) = False
isNonExpansive (TmVar _) = True
isNonExpansive (TmAbs _ _) = True
isNonExpansive (TmLet _ t1 t2) = isNonExpansive t1 && isNonExpansive t2
isNonExpansive _ = True
dangerousVar :: Type -> Either Error (Map.Map VarName Kind)
dangerousVar (TyVar _) = return Map.empty
dangerousVar (TyArrow t1 t2) = do
d1 <- fvType t1
d2 <- dangerousVar t2
mapUnionWithKind d1 d2
dangerousVar (TyRecord r) = dangerousVarRow r
dangerousVar (TyVariant r) = dangerousVarRow r
dangerousVar (TyMu x t) = do
dt <- dangerousVar t
case Map.lookup x dt of
Nothing -> return dt
Just k -> Left (ErrVarKindConflict x KProper k)
dangerousVar t = fvType t
dangerousVarRow :: TypeRow -> Either Error (Map.Map VarName Kind)
dangerousVarRow (RowPresence _label p r) = do
dp <- dangerousVarPresence p
dr <- dangerousVarRow r
mapUnionWithKind dp dr
dangerousVarRow (RowMu x r) = do
dr <- dangerousVarRow r
case Map.lookup x dr of
Nothing -> return dr
Just KRow -> fvRow (RowMu x r)
Just k -> Left (ErrVarKindConflict x KRow k)
dangerousVarRow RowEmpty = return Map.empty
dangerousVarPresence :: TypePresence -> Either Error (Map.Map VarName Kind)
dangerousVarPresence (Present t) = dangerousVar t
for record , mark generalization of PresenceVarWithType safe
dangerousVarPresence (PresenceVarWithType _ t) = dangerousVar t
dangerousVarPresence p = fvPresence p
replaceSafePresent :: (MonadError Error m, MonadState InferenceState m) => Type -> m Type
replaceSafePresent (TyArrow t1 t2) = TyArrow t1 <$> replaceSafePresent t2
replaceSafePresent (TyMu x t) = do
dt <- liftEither (dangerousVar t)
case Map.lookup x dt of
Nothing -> TyMu x <$> replaceSafePresent t
Just k -> throwError (ErrVarKindConflict x KProper k)
replaceSafePresent (TyRecord r) = TyRecord <$> replaceSafePresentRow True r
replaceSafePresent (TyVariant r) = TyVariant <$> replaceSafePresentRow False r
replaceSafePresent t = return t
replaceSafePresentRow :: (MonadError Error m, MonadState InferenceState m) => Bool -> TypeRow -> m TypeRow
replaceSafePresentRow shouldReplace (RowPresence label p r) =
RowPresence label
<$> replaceSafePresentPresence shouldReplace p
<*> replaceSafePresentRow shouldReplace r
replaceSafePresentRow shouldReplace (RowMu x r) = do
dr <- liftEither (dangerousVarRow r)
case Map.lookup x dr of
Nothing -> RowMu x <$> replaceSafePresentRow shouldReplace r
Just k -> throwError (ErrVarKindConflict x KRow k)
replaceSafePresentRow _shouldReplace r = return r
replaceSafePresentPresence :: (MonadError Error m, MonadState InferenceState m) => Bool -> TypePresence -> m TypePresence
replaceSafePresentPresence shouldReplace (Present t) =
if shouldReplace
then do
x <- newVarInner KPresenceWithType
PresenceVarWithType x <$> replaceSafePresent t
else Present <$> replaceSafePresent t
replaceSafePresentPresence _shouldReplace (PresenceVarWithType x t) =
PresenceVarWithType x <$> replaceSafePresent t
replaceSafePresentPresence _shouldReplace p = return p
replacePrefix ::
(MonadState InferenceState m, MonadError Error m) =>
Map.Map VarName Kind ->
m (Map.Map VarName TypeSubstituter, Map.Map VarName Kind)
replacePrefix m = do
resetVarPrefix kindPrefixes
nameMap <- sequence (Map.map (newVar . kindToPrefix) m)
let inv = Map.fromList [(v, k) | (k, v) <- Map.toList nameMap]
kindMap = Map.map (m Map.!) inv
substMap <- liftEither (sequence (Map.intersectionWith varToTySub m nameMap))
return (substMap, kindMap)
ensureProper :: (MonadError Error m) => TypeSubstituter -> m Type
ensureProper (TySubProper t) = return t
ensureProper s = throwError (ErrUnifyKindMismatch KProper (kindOfTySub s))
ensurePresence :: (MonadError Error m) => TypeSubstituter -> m TypePresence
ensurePresence (TySubPresence p) = return p
ensurePresence s = throwError (ErrUnifyKindMismatch KPresence (kindOfTySub s))
ensurePresenceWithType ::
(MonadError Error m) => TypeSubstituter -> m PresenceWithType
ensurePresenceWithType (TySubPresenceWithType p) = return p
ensurePresenceWithType s =
throwError (ErrUnifyKindMismatch KPresenceWithType (kindOfTySub s))
ensureRow :: (MonadError Error m) => TypeSubstituter -> m TypeRow
ensureRow (TySubRow r) = return r
ensureRow s = throwError (ErrUnifyKindMismatch KRow (kindOfTySub s))
unifyProper :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => MonadUnify s m => Type -> Type -> m ()
unifyProper t1 t2 = do
t1' <- classDesc (TySubProper t1) >>= ensureProper
t2' <- classDesc (TySubProper t2) >>= ensureProper
if t1' == t2'
then return ()
else case (t1', t2') of
(TyVar x1, _) -> equate (TySubProper (TyVar x1)) (TySubProper t2')
(_, TyVar x2) -> equate (TySubProper (TyVar x2)) (TySubProper t1')
_ -> do
equate (TySubProper t1') (TySubProper t2')
unifyProper' :: (MonadUnify s m, MonadError Error m, MonadState InferenceState m) => Type -> Type -> m ()
unifyProper' (TyArrow t11 t12) (TyArrow t21 t22) =
unifyProper t11 t21 >> unifyProper t12 t22
unifyProper' (TyRecord r1) (TyRecord r2) = unifyRow r1 r2
unifyProper' (TyVariant r1) (TyVariant r2) = unifyRow r1 r2
unifyProper' (TyRef t1) (TyRef t2) = unifyProper t1 t2
unifyProper' t1 t2 =
throwError (ErrUnifyNoRuleApplied (TySubProper t1) (TySubProper t2))
unifyPresenceWithType :: (MonadError Error m, MonadUnify s m) => PresenceWithType -> PresenceWithType -> m ()
unifyPresenceWithType p1 p2 = do
p1' <- classDesc (TySubPresenceWithType p1) >>= ensurePresenceWithType
p2' <- classDesc (TySubPresenceWithType p2) >>= ensurePresenceWithType
if p1' == p2'
then return ()
else case (p1', p2') of
(PresenceWithTypeVar x1, _) ->
equate
(TySubPresenceWithType (PresenceWithTypeVar x1))
(TySubPresenceWithType p2')
(_, PresenceWithTypeVar x2) ->
equate
(TySubPresenceWithType (PresenceWithTypeVar x2))
(TySubPresenceWithType p1')
_ ->
throwError
( ErrUnifyNoRuleApplied
(TySubPresenceWithType p1')
(TySubPresenceWithType p2')
)
unifyPresence :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypePresence -> TypePresence -> m ()
unifyPresence p1 p2 = do
p1' <- classDesc (TySubPresence p1) >>= ensurePresence
p2' <- classDesc (TySubPresence p2) >>= ensurePresence
if p1' == p2'
then return ()
else case (p1', p2') of
(PresenceVar x1, _) ->
equate (TySubPresence (PresenceVar x1)) (TySubPresence p2')
(_, PresenceVar x2) ->
equate (TySubPresence (PresenceVar x2)) (TySubPresence p1')
_ -> unifyPresence' p1' p2'
unifyPresence' :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypePresence -> TypePresence -> m ()
unifyPresence' (Present t1) (Present t2) = unifyProper t1 t2
unifyPresence' (PresenceVarWithType x1 _) Absent =
unifyPresenceWithType (PresenceWithTypeVar x1) PresenceWithTypeAbsent
unifyPresence' (PresenceVarWithType x1 t1) (Present t2) =
unifyPresenceWithType (PresenceWithTypeVar x1) PresenceWithTypePresent
>> unifyProper t1 t2
unifyPresence' (PresenceVarWithType x1 t1) (PresenceVarWithType x2 t2) =
unifyPresenceWithType (PresenceWithTypeVar x1) (PresenceWithTypeVar x2)
>> unifyProper t1 t2
unifyPresence' Absent (PresenceVarWithType x2 _) =
unifyPresenceWithType (PresenceWithTypeVar x2) PresenceWithTypeAbsent
unifyPresence' (Present t1) (PresenceVarWithType x2 t2) =
unifyPresenceWithType (PresenceWithTypeVar x2) PresenceWithTypePresent
>> unifyProper t1 t2
unifyPresence' p1 p2 =
throwError (ErrUnifyNoRuleApplied (TySubPresence p1) (TySubPresence p2))
unifyRow :: (MonadError Error m, MonadUnify s m, MonadState InferenceState m) => TypeRow -> TypeRow -> m ()
unifyRow r1 r2 = do
r1' <- classDesc (TySubRow r1) >>= ensureRow
r2' <- classDesc (TySubRow r2) >>= ensureRow
if r1' == r2'
then return ()
else case (r1', r2') of
(RowVar x1, _) -> equate (TySubRow (RowVar x1)) (TySubRow r2')
(_, RowVar x2) -> equate (TySubRow (RowVar x2)) (TySubRow r1')
_ -> do
unifyRow' :: (MonadError Error m, MonadState InferenceState m, MonadUnify s m) => TypeRow -> TypeRow -> m ()
unifyRow' RowEmpty (RowPresence _l p r) =
unifyPresence p Absent >> unifyRow r RowEmpty
unifyRow' (RowPresence _l p r) RowEmpty =
unifyPresence p Absent >> unifyRow r RowEmpty
unifyRow' (RowPresence l1 p1 r1) (RowPresence l2 p2 r2) =
if l1 == l2
then unifyPresence p1 p2 >> unifyRow r1 r2
else do
r3 <- newVarInner KRow
let r3' = RowVar r3
unifyRow r1 (RowPresence l2 p2 r3')
unifyRow r2 (RowPresence l1 p1 r3')
unifyRow' r1 r2 =
throwError (ErrUnifyNoRuleApplied (TySubRow r1) (TySubRow r2))
describeScheme :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypeScheme -> m TypeScheme
describeScheme allowMu ctx (ScmForall x k s) =
ScmForall x k <$> describeScheme allowMu (Set.insert x ctx) s
describeScheme allowMu ctx (ScmMono t) =
ScmMono <$> describeProper allowMu ctx t
describeProper :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> Type -> m Type
describeProper _ ctx (TyVar x) | x `Set.member` ctx = return (TyVar x)
describeProper allowMu ctx (TyVar x) = do
t <- classDesc (TySubProper (TyVar x)) >>= ensureProper
if t == TyVar x
then return (TyVar x)
else do
t' <- describeProper allowMu (Set.insert x ctx) t
fv <- liftEither (fvType t')
case Map.lookup x fv of
Nothing -> return t'
Just KProper -> return (TyMu x t')
Just k -> throwError (ErrVarKindConflict x KProper k)
describeProper allowMu ctx (TyArrow t1 t2) =
TyArrow <$> describeProper allowMu ctx t1 <*> describeProper allowMu ctx t2
describeProper allowMu ctx (TyRecord row) =
TyRecord <$> describeRow allowMu ctx row
describeProper allowMu ctx (TyVariant row) =
TyVariant <$> describeRow allowMu ctx row
describeProper allowMu ctx (TyRef t) = TyRef <$> describeProper allowMu ctx t
describeProper allowMu ctx (TyMu x t) =
if allowMu
then TyMu x <$> describeProper allowMu (Set.insert x ctx) t
else throwError (ErrCanNotHandleMuType (TyMu x t))
describeProper _ _ TyInteger = return TyInteger
describeProper _ _ TyChar = return TyChar
describePresence ::
(MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypePresence -> m TypePresence
describePresence _ _ Absent = return Absent
describePresence allowMu ctx (Present t) =
Present <$> describeProper allowMu ctx t
describePresence allowMu ctx (PresenceVar x) = do
p <- classDesc (TySubPresence (PresenceVar x)) >>= ensurePresence
if p == PresenceVar x
then return (PresenceVar x)
else describePresence allowMu ctx p
describePresence allowMu ctx (PresenceVarWithType x t) = do
pt <- describePresenceWithType allowMu ctx (PresenceWithTypeVar x)
case pt of
PresenceWithTypeAbsent -> return Absent
PresenceWithTypePresent -> Present <$> describeProper allowMu ctx t
PresenceWithTypeVar x' ->
PresenceVarWithType x' <$> describeProper allowMu ctx t
describePresenceWithType :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> PresenceWithType -> m PresenceWithType
describePresenceWithType _ _ PresenceWithTypeAbsent =
return PresenceWithTypeAbsent
describePresenceWithType _ _ PresenceWithTypePresent =
return PresenceWithTypePresent
describePresenceWithType allowMu ctx (PresenceWithTypeVar x) = do
pt <-
classDesc (TySubPresenceWithType (PresenceWithTypeVar x))
>>= ensurePresenceWithType
if pt == PresenceWithTypeVar x
then return (PresenceWithTypeVar x)
else describePresenceWithType allowMu ctx pt
describeRow :: (MonadError Error m, MonadUnify s m) => Bool -> Set.Set VarName -> TypeRow -> m TypeRow
describeRow _ _ RowEmpty = return RowEmpty
describeRow _ ctx (RowVar x) | x `Set.member` ctx = return (RowVar x)
describeRow allowMu ctx (RowVar x) = do
r <- classDesc (TySubRow (RowVar x)) >>= ensureRow
if r == RowVar x
then return (RowVar x)
else do
r' <- describeRow allowMu (Set.insert x ctx) r
fv <- liftEither (fvRow r')
case Map.lookup x fv of
Nothing -> return r'
Just KRow -> return (RowMu x r')
Just k -> throwError (ErrVarKindConflict x KRow k)
describeRow allowMu ctx (RowPresence l p r) =
RowPresence l <$> describePresence allowMu ctx p <*> describeRow allowMu ctx r
describeRow allowMu ctx (RowMu x r) =
if allowMu
then RowMu x <$> describeRow allowMu (Set.insert x ctx) r
else throwError (ErrCanNotHandleMuRow (RowMu x r))
regTreeEq ' t1 t2 = case ( runMaybeT ( regTreeEq t1 t2 ) ) Set.empty of
regTreeEq t1 t2 = gets ( Set.member ( t1 , t2 ) ) > > = \case
( TyNat , TyNat ) - > return ( )
( TyArrow t11 t12 , TyArrow t21 t22 ) - >
regTreeEq t11 t21 > > regTreeEq t12 t22
( TyRef t1 ' , TyRef t2 ' ) - > regTreeEq t1 ' t2 '
( TyRecord r1 , TyRecord r2 ) - > regTreeEqRow r1 r2
( TyVar x1 , TyVar x2 ) | x1 = = x2 - > return ( )
regTreeEq ( applySubst ( Map.singleton x1 ( TySubProper t1 ) ) t12 ) t2
( _ , ) - >
regTreeEq t1 ( applySubst ( Map.singleton x2 ( TySubProper t2 ) ) t22 )
= >
= sequence _ ( Map.intersectionWith regTreeEqPresence )
> > case ( cof1 , ) of
|
52d00d54e3c3b5238ccd04bb4e3a6389462470df9a076592882ade8ce494a6d6 | marick/structural-typing | predicate_defining.clj | (ns structural-typing.assist.predicate-defining
"Helpers for defining custom predicates. See `structural-typing.preds` for examples of use."
(:use structural-typing.clojure.core)
(:require [structural-typing.assist.oopsie :as oopsie]
[structural-typing.assist.format :as format]
[structural-typing.guts.preds.annotating :as annotating]
[such.readable :as readable])
(:refer-clojure :exclude [any?]))
(defn should-be
"The typical explanation string is built from a path, expected value,
and leaf value, in that order. The path and leaf value can be gotten from
an [[oopsie]]. This, then, is shorthand that lets you build an explainer
function from just a format string and an expected value.
(should-be \"%s should be a member of `%s`; it is `%s`\" coll)
"
[format-string expected]
#(format format-string,
(oopsie/friendly-path %)
(readable/value-string expected)
(readable/value-string (:leaf-value %))))
(defn compose-predicate
"A checker can be any function. But it's often more useful to \"compose\" a checker
predicate from three parts: its name to be printed (such as `\"(member [1 2 3])\"`),
a function, and an explainer function that converts an [[oopsie]] into a string. This
function creates a checker function from those three parts.
Note that `expected` is formatted as a readable value. So, for example, strings appear
in the explanation surrounded by quotes.
The resulting predicate still returns the same values as the second argument (the
\"underlying\" predicate), but it has extra metadata."
[name pred fmt-fn]
(->> pred
(annotating/show-as name)
(annotating/explain-with fmt-fn)))
| null | https://raw.githubusercontent.com/marick/structural-typing/9b44c303dcfd4a72c5b75ec7a1114687c809fba1/src/structural_typing/assist/predicate_defining.clj | clojure | (ns structural-typing.assist.predicate-defining
"Helpers for defining custom predicates. See `structural-typing.preds` for examples of use."
(:use structural-typing.clojure.core)
(:require [structural-typing.assist.oopsie :as oopsie]
[structural-typing.assist.format :as format]
[structural-typing.guts.preds.annotating :as annotating]
[such.readable :as readable])
(:refer-clojure :exclude [any?]))
(defn should-be
"The typical explanation string is built from a path, expected value,
and leaf value, in that order. The path and leaf value can be gotten from
an [[oopsie]]. This, then, is shorthand that lets you build an explainer
function from just a format string and an expected value.
(should-be \"%s should be a member of `%s`; it is `%s`\" coll)
"
[format-string expected]
#(format format-string,
(oopsie/friendly-path %)
(readable/value-string expected)
(readable/value-string (:leaf-value %))))
(defn compose-predicate
"A checker can be any function. But it's often more useful to \"compose\" a checker
predicate from three parts: its name to be printed (such as `\"(member [1 2 3])\"`),
a function, and an explainer function that converts an [[oopsie]] into a string. This
function creates a checker function from those three parts.
Note that `expected` is formatted as a readable value. So, for example, strings appear
in the explanation surrounded by quotes.
The resulting predicate still returns the same values as the second argument (the
\"underlying\" predicate), but it has extra metadata."
[name pred fmt-fn]
(->> pred
(annotating/show-as name)
(annotating/explain-with fmt-fn)))
| |
8b937d10a1f3d695256e93b1e29e46812663f56bd4b61ca9f78d395fe6d88ad5 | kind2-mc/kind2 | lustreExpr.ml | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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
-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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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
-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.
*)
open Lib
(* Abbreviations *)
module I = LustreIdent
module SVS = StateVar.StateVarSet
module VS = Var.VarSet
(* Exceptions *)
exception Type_mismatch
exception NonConstantShiftOperand
(* A Lustre expression is a term *)
type expr = Term.t
(* Lift of [Term.is_true]. *)
let is_true_expr e = e = Term.t_true
(* A Lustre type is a type *)
type lustre_type = Type.t
A typed expression
type t = {
(* Lustre expression for the initial state *)
expr_init: expr;
(* Lustre expression after initial state *)
expr_step: expr;
(* Type of expression
Keep the type here instead of reading from expr_init or
expr_step, otherwise we need to get both types and merge *)
expr_type: Type.t
}
(* Bound for index variable, or fixed value for index variable *)
type 'a bound_or_fixed =
| Bound of 'a (* Upper bound for index variable *)
| Fixed of 'a (* Fixed value for index variable *)
| Unbound of 'a (* unbounded index variable *)
let compare_expr = Term.compare
(* Total order on expressions *)
let compare
{ expr_init = init1; expr_step = step1 }
{ expr_init = init2; expr_step = step2 } =
comparision of initial value , step value
let c_init = compare_expr init1 init2 in
if c_init = 0 then compare_expr step1 step2 else c_init
(* Equality on expressions *)
let equal
{ expr_init = init1; expr_step = step1 }
{ expr_init = init2; expr_step = step2 } =
Term.equal init1 init2 && Term.equal step1 step2
(* Hashing of expressions *)
let hash { expr_init; expr_step } =
Hashtbl.hash
(Term.hash expr_init, Term.hash expr_step)
Map on expression
We want to use the constructors of this module instead of the
functions of the term module to get type checking and
simplification . Therefore the function [ f ] gets values of type [ t ] ,
not of type [ expr ] .
A expression of type [ t ] has the [ - > ] only at the top with
the [ expr_init ] as the left operand and [ expr_step ] as the
right . We apply Term.map separately to [ expr_init ] and [ expr_step ] ,
which are of type [ expr = Term.t ] and construct a new Lustre
expression from the result .
When mapping [ expr_init ] , we know that we are on the left side of a
[ - > ] operator . If the result of [ f ] is [ l - > r ] we always take [ l ] ,
because [ ( l - > r ) - > t = ( l - > t ) ] . Same for [ expr_step ] , because
[ t - > ( l - > r ) = t - > r ] .
We want to use the constructors of this module instead of the
functions of the term module to get type checking and
simplification. Therefore the function [f] gets values of type [t],
not of type [expr].
A Lustre expression of type [t] has the [->] only at the top with
the [expr_init] as the left operand and [expr_step] as the
right. We apply Term.map separately to [expr_init] and [expr_step],
which are of type [expr = Term.t] and construct a new Lustre
expression from the result.
When mapping [expr_init], we know that we are on the left side of a
[->] operator. If the result of [f] is [l -> r] we always take [l],
because [(l -> r) -> t = (l -> t)]. Same for [expr_step], because
[t -> (l -> r) = t -> r].
*)
let map f { expr_init; expr_step } =
(* Create a Lustre expression from a term and return a term, if
[init] is true considering [expr_init] only, otherwise [expr_step]
only. *)
let f' init i term =
Construct Lustre expression from term , using the term for both
the initial state and the step state
the initial state and the step state *)
let expr =
{ expr_init = term;
expr_step = term;
expr_type = Term.type_of_term term }
in
Which of Init or step ?
if init then
(* Return term for initial state *)
(f i expr).expr_init
else
(* Return term for step state *)
(f i expr).expr_step
in
(* Apply function separately to init and step expression and
rebuild *)
let expr_init = Term.map (f' true) expr_init in
let expr_step = Term.map (f' false) expr_step in
let expr_type = Term.type_of_term expr_init in
{ expr_init; expr_step; expr_type }
let map_vars_expr = Term.map_vars
let map_vars f { expr_init = i; expr_step = s; expr_type = t } = {
expr_init = map_vars_expr f i;
expr_step = map_vars_expr f s;
expr_type = t
}
let rec map_top ' f term = match Term . T.node_of_t term with
| Term . T.FreeVar _ - > f term
| Term . T.Node ( s , _ ) when Symbol.equal_symbols s Symbol.s_select - > f term
| Term . term
| Term . T.Leaf _ - > term
| Term . T.Node ( s , l ) - > Term . T.mk_app s ( List.map ( map_array_var ' f ) l )
| Term . T.Let ( l , t ) - >
Term . T.mk_let_of_lambda ( map_array_var '' f l ) ( List.map ( map_array_var ' f ) t )
| Term . T.Exists l - >
Term . T.mk_exists_of_lambda ( map_array_var '' f l )
| Term . T.Forall l - >
Term . T.mk_forall_of_lambda ( map_array_var '' f l )
| Term . T.Annot ( t , a ) - > Term . T.mk_annot ( map_array_var ' f t ) a
and map_array_var '' f lambda = match Term . T.node_of_lambda lambda with
| Term . T.L ( l , t ) - > Term . T.mk_lambda_of_term l ( map_array_var ' f t )
let map_array_var f ( { expr_init ; expr_step } as expr ) =
{ expr with
expr_init = map_array_var ' f ' expr_init ;
expr_step = map_array_var ' f ' expr_step }
let rec map_top' f term = match Term.T.node_of_t term with
| Term.T.FreeVar _ -> f term
| Term.T.Node (s, _) when Symbol.equal_symbols s Symbol.s_select -> f term
| Term.T.BoundVar _ -> term
| Term.T.Leaf _ -> term
| Term.T.Node (s, l) -> Term.T.mk_app s (List.map (map_array_var' f) l)
| Term.T.Let (l, t) ->
Term.T.mk_let_of_lambda (map_array_var'' f l) (List.map (map_array_var' f) t)
| Term.T.Exists l ->
Term.T.mk_exists_of_lambda (map_array_var'' f l)
| Term.T.Forall l ->
Term.T.mk_forall_of_lambda (map_array_var'' f l)
| Term.T.Annot (t, a) -> Term.T.mk_annot (map_array_var' f t) a
and map_array_var'' f lambda = match Term.T.node_of_lambda lambda with
| Term.T.L (l, t) -> Term.T.mk_lambda_of_term l (map_array_var' f t)
let map_array_var f ({ expr_init; expr_step } as expr) =
{ expr with
expr_init = map_array_var' f' expr_init;
expr_step = map_array_var' f' expr_step }
*)
(* Return the type of the expression *)
let type_of_lustre_expr { expr_type } = expr_type
let type_of_expr e = Term.type_of_term e
Hash table over expressions
module LustreExprHashtbl = Hashtbl.Make
(struct
type z = t
type t = z (* avoid cyclic type abbreviation *)
let equal = equal
let hash = hash
end)
(* Equality on expressions *)
let equal_expr = Term.equal
(* These offsets are different from the offsets in the transition system,
because here we want to know if the initial and the step
expressions are equal without bumping offsets. *)
Offset of state variable at first instant
let base_offset = Numeral.zero
Offset of state variable at first instant
let pre_base_offset = Numeral.(pred base_offset)
(* Offset of state variable at current instant *)
let cur_offset = base_offset
(* Offset of state variable at previous instant *)
let pre_offset = Numeral.(pred cur_offset)
(* ********************************************************************** *)
(* Pretty-printing *)
(* ********************************************************************** *)
(* Pretty-print a type as a Lustre type *)
let rec pp_print_lustre_type safe ppf t = match Type.node_of_type t with
| Type.Bool -> Format.pp_print_string ppf "bool"
| Type.Int -> Format.pp_print_string ppf "int"
| Type.IntRange (i, j, Type.Range) ->
Format.fprintf
ppf
"subrange [%a, %a] of int"
Numeral.pp_print_numeral i
Numeral.pp_print_numeral j
| Type.Real -> Format.pp_print_string ppf "real"
| Type.Abstr s -> Format.pp_print_string ppf s
| Type.IntRange (_, _, Type.Enum) ->
let cs = Type.constructors_of_enum t in
Format.fprintf ppf "enum {%a}"
(pp_print_list Format.pp_print_string ", ") cs
| Type.UBV i ->
begin match i with
| 8 -> Format.pp_print_string ppf "uint8"
| 16 -> Format.pp_print_string ppf "uint16"
| 32 -> Format.pp_print_string ppf "uint32"
| 64 -> Format.pp_print_string ppf "uint64"
| _ -> raise
(Invalid_argument "pp_print_lustre_type: UBV size not allowed")
end
| Type.BV i ->
begin match i with
| 8 -> Format.pp_print_string ppf "int8"
| 16 -> Format.pp_print_string ppf "int16"
| 32 -> Format.pp_print_string ppf "int32"
| 64 -> Format.pp_print_string ppf "int64"
| _ -> raise
(Invalid_argument "pp_print_lustre_type: BV size not allowed")
end
| Type.Array (s, _) ->
Format.fprintf ppf "array of %a" (pp_print_lustre_type safe) s
String representation of a symbol in
let string_of_symbol = function
| `TRUE -> "true"
| `FALSE -> "false"
| `NOT -> "not"
| `IMPLIES -> "=>"
| `AND -> "and"
| `OR -> "or"
| `EQ -> "="
| `NUMERAL n -> Numeral.string_of_numeral n
| `DECIMAL d -> Decimal.string_of_decimal_lustre d
| `XOR -> "xor"
| `UBV b ->
(match Bitvector.length_of_bitvector b with
| 8 -> "(uint8 " ^ (Numeral.string_of_numeral (Bitvector.ubv8_to_num b)) ^ ")"
| 16 -> "(uint16 " ^ (Numeral.string_of_numeral (Bitvector.ubv16_to_num b)) ^ ")"
| 32 -> "(uint32 " ^ (Numeral.string_of_numeral (Bitvector.ubv32_to_num b)) ^ ")"
| 64 -> "(uint64 " ^ (Numeral.string_of_numeral (Bitvector.ubv64_to_num b)) ^ ")"
| _ -> raise Type_mismatch)
| `BV b ->
(match Bitvector.length_of_bitvector b with
| 8 -> "(int8 " ^ (Numeral.string_of_numeral (Bitvector.bv8_to_num b)) ^ ")"
| 16 -> "(int16 " ^ (Numeral.string_of_numeral (Bitvector.bv16_to_num b)) ^ ")"
| 32 -> "(int32 " ^ (Numeral.string_of_numeral (Bitvector.bv32_to_num b)) ^ ")"
| 64 -> "(int64 " ^ (Numeral.string_of_numeral (Bitvector.bv64_to_num b)) ^ ")"
| _ -> raise Type_mismatch)
| `MINUS -> "-"
| `PLUS -> "+"
| `TIMES -> "*"
| `DIV -> "/"
| `INTDIV ->"div"
| `MOD -> "mod"
| `ABS -> "abs"
| `LEQ -> "<="
| `LT -> "<"
| `GEQ -> ">="
| `GT -> ">"
| `TO_REAL -> "real"
| `TO_INT -> "int"
| `TO_UINT8 -> "uint8"
| `TO_UINT16 -> "uint16"
| `TO_UINT32 -> "uint32"
| `TO_UINT64 -> "uint64"
| `TO_INT8 -> "int8"
| `TO_INT16 -> "int16"
| `TO_INT32 -> "int32"
| `TO_INT64 -> "int64"
| `BVAND -> "&&"
| `BVOR -> "||"
| `BVNOT -> "!"
| `BVNEG -> "-"
| `BVADD -> "+"
| `BVSUB -> "-"
| `BVMUL -> "*"
| `BVUDIV -> "div"
| `BVSDIV -> "div"
| `BVUREM -> "mod"
| `BVSREM -> "mod"
| `BVULT -> "<"
| `BVULE -> "<="
| `BVUGT -> ">"
| `BVUGE -> ">="
| `BVSLT -> "<"
| `BVSLE -> "<="
| `BVSGT -> ">"
| `BVSGE -> ">="
| `BVSHL -> "lshift"
| `BVLSHR -> "rshift"
| `BVASHR -> "arshift"
| `BVEXTRACT (i,j) -> "(_ extract " ^ (Numeral.string_of_numeral i) ^ " " ^ (Numeral.string_of_numeral j) ^ ")"
| `BVCONCAT -> "concat"
| `BVSIGNEXT i -> "(_ sign_extend " ^ (Numeral.string_of_numeral i) ^ ")"
| _ -> failwith "string_of_symbol"
(* Pretty-print a symbol with a given type *)
let pp_print_symbol_as_type as_type ppf s =
match as_type, s with
| Some ty, `NUMERAL n when Type.is_enum ty ->
Type.get_constr_of_num n
|> Format.pp_print_string ppf
| _ ->
Format.pp_print_string ppf (string_of_symbol s)
(* Pretty-print a symbol as is *)
let pp_print_symbol ppf s =
Format.pp_print_string ppf (string_of_symbol s)
(* Pretty-print a variable *)
let pp_print_lustre_var _ ppf state_var =
Format.fprintf ppf "%s" (StateVar.name_of_state_var state_var)
(* Pretty-printa variable with its type *)
let pp_print_lustre_var_typed safe ppf state_var =
Format.fprintf ppf
"%t%a: %a"
(function ppf ->
if StateVar.is_const state_var then Format.fprintf ppf "const ")
(pp_print_lustre_var safe) state_var
(pp_print_lustre_type safe) (StateVar.type_of_state_var state_var)
(* Pretty-print a variable under [depth] pre operators *)
let rec pp_print_var pvar ppf var =
(* Variable is at an instant *)
if Var.is_state_var_instance var then
(* Get state variable of variable *)
let state_var = Var.state_var_of_state_var_instance var in
(* Function to pretty-print a variable with or without pre *)
let pp =
(* Variable at current offset *)
if Numeral.equal (Var.offset_of_state_var_instance var) cur_offset then
Format.fprintf ppf
"@[<hv 2>%a@]"
pvar
(* Variable at previous offset *)
else if Numeral.equal (Var.offset_of_state_var_instance var) pre_offset then
Format.fprintf ppf
"@[<hv 2>(pre %a)@]"
pvar
(* Fail on other offsets *)
else
function _ -> raise (Invalid_argument "pp_print_var")
in
(* Pretty-print state variable with or without pre *)
pp state_var
(* Variable is constant *)
else if Var.is_const_state_var var then
(* Get state variable of variable *)
let state_var = Var.state_var_of_state_var_instance var in
Format.fprintf ppf
"@[<hv 2>%a@]"
pvar
state_var
(* Fail on other types of variables *)
else
(* free variable *)
Format.fprintf ppf "%s" (Var.string_of_var var)
(* Pretty-print a term *)
and pp_print_term_node ?as_type safe pvar ppf t = match Term.T.destruct t with
| Term.T.Var var -> pp_print_var pvar ppf var
| Term.T.Const s ->
pp_print_symbol_as_type as_type ppf (Symbol.node_of_symbol s)
| Term.T.App (s, l) ->
pp_print_app ?as_type safe pvar ppf (Symbol.node_of_symbol s) l
| Term . T.Attr ( t , _ ) - >
pp_print_term_node ? as_type safe pvar ppf t
pp_print_term_node ?as_type safe pvar ppf t *)
| exception Invalid_argument ex -> (
match Term.T.node_of_t t with
| Term.T.Forall l -> (match Term.T.node_of_lambda l with
Term.T.L (_,t) -> (Format.fprintf ppf
"@[<hv 1>forall@ @[<hv 1>(...)@ %a@]@]"
(pp_print_term_node ?as_type safe pvar) t))
| Term.T.Exists l -> (match Term.T.node_of_lambda l with
Term.T.L (_,t) -> (Format.fprintf ppf
"@[<hv 1>exists@ @[<hv 1>(...)@ %a@]@]"
(pp_print_term_node ?as_type safe pvar) t))
| Term.T.BoundVar _ -> Term.T.pp_print_term ppf t
| _ -> raise (Invalid_argument ex)
)
Pretty - print the second and following arguments of a
left - associative function application
left-associative function application *)
and pp_print_app_left' safe pvar s ppf = function
| h :: tl ->
Format.fprintf ppf
" %a@ %a%t"
pp_print_symbol s
(pp_print_term_node safe pvar) h
(function ppf -> pp_print_app_left' safe pvar s ppf tl)
| [] -> ()
(* Pretty-print a left-associative function application
Print (+ a b c) as (a + b + c) *)
and pp_print_app_left safe pvar s ppf = function
(* Function application must have arguments, is a constant
otherwise *)
| [] -> assert false
Print first argument
| h :: tl ->
Format.fprintf ppf
"@[<hv 2>(%a%t)@]"
(pp_print_term_node safe pvar) h
(function ppf -> pp_print_app_left' safe pvar s ppf tl)
(* Pretty-print arguments of a right-associative function application *)
and pp_print_app_right' safe pvar s arity ppf = function
(* Function application must have arguments, is a constant
otherwise *)
| [] -> assert false
(* Last or only argument *)
| [h] ->
(* Print closing parentheses for all arguments *)
let rec aux ppf = function
| 0 -> ()
| i ->
Format.fprintf ppf
"%t)@]"
(function ppf -> aux ppf (pred i))
in
(* Print last argument and close all parentheses *)
Format.fprintf ppf
"%a%t"
(pp_print_term_node safe pvar) h
(function ppf -> aux ppf arity)
Second last or earlier argument
| h :: tl ->
(* Open parenthesis and print argument *)
Format.fprintf ppf
"@[<hv 2>(%a %a@ %t"
(pp_print_term_node safe pvar) h
pp_print_symbol s
(function ppf -> pp_print_app_right' safe pvar s arity ppf tl)
(* Pretty-print a right-associative function application
Print (=> a b c) as (a => (b => c)) *)
and pp_print_app_right safe pvar s ppf l =
pp_print_app_right' safe pvar s (List.length l - 1) ppf l
(* Pretty-print a chaining function application
Print (= a b c) as (a = b) and (b = c) *)
and pp_print_app_chain safe pvar s ppf = function
Chaining function application must have more than one argument
| []
| [_] -> assert false
(* Last or only pair of arguments *)
| [l; r] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
Print function application of first pair , conjunction and continue
| l :: r :: tl ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a) and %a@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
(pp_print_app_chain safe pvar s) (r :: tl)
(* Pretty-print a function application *)
and pp_print_app ?as_type safe pvar ppf = function
(* Function application must have arguments, cannot have nullary
symbols here *)
| `TRUE
| `FALSE
| `NUMERAL _
| `DECIMAL _
| `UBV _
| `BV _
| `BV2NAT -> (function _ -> assert false)
Unary symbols
| `NOT
| `BVNOT
| `BVNEG
| `TO_REAL
| `TO_INT
| `UINT8_TO_INT
| `UINT16_TO_INT
| `UINT32_TO_INT
| `UINT64_TO_INT
| `INT8_TO_INT
| `INT16_TO_INT
| `INT32_TO_INT
| `INT64_TO_INT
| `TO_UINT8
| `TO_UINT16
| `TO_UINT32
| `TO_UINT64
| `TO_INT8
| `TO_INT16
| `TO_INT32
| `TO_INT64
| `BVEXTRACT _
| `BVSIGNEXT _
| `ABS as s ->
(function [a] ->
Format.fprintf ppf
"@[<hv 2>(%a@ %a)@]"
pp_print_symbol s
(pp_print_term_node safe pvar) a
| _ -> assert false)
Unary and left - associative binary symbols
| `MINUS as s ->
(function
| [] -> assert false
| [a] ->
Format.fprintf ppf
"%a%a"
pp_print_symbol s
(pp_print_term_node safe pvar) a
| _ as l -> pp_print_app_left safe pvar s ppf l)
Binary left - associative symbols with two or more arguments
| `AND
| `OR
| `XOR
| `BVAND
| `BVOR
| `BVADD
| `BVSUB
| `BVMUL
| `BVUDIV
| `BVSDIV
| `BVUREM
| `BVSREM
| `PLUS
| `TIMES
| `DIV
| `INTDIV as s ->
(function
| []
| [_] -> assert false
| _ as l -> pp_print_app_left safe pvar s ppf l)
(* Binary right-associative symbols *)
| `IMPLIES as s -> pp_print_app_right safe pvar s ppf
(* Chainable binary symbols *)
| `EQ
| `BVULT
| `BVULE
| `BVUGT
| `BVUGE
| `BVSLT
| `BVSLE
| `BVSGT
| `BVSGE
| `LEQ
| `LT
| `GEQ
| `GT as s -> pp_print_app_chain safe pvar s ppf
(* Binary non-associative symbols *)
| `BVSHL
| `BVLSHR
| `BVASHR as s ->
(function
| [a;b] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) a
pp_print_symbol s
(pp_print_term_node safe pvar) b
| _ -> assert false)
(* if-then-else *)
| `ITE ->
(function [p; l; r] ->
Format.fprintf ppf
"(if %a then %a else %a)"
(pp_print_term_node safe pvar) p
(pp_print_term_node ?as_type safe pvar) l
(pp_print_term_node ?as_type safe pvar) r
| _ -> assert false)
(* Binary symbols *)
| `MOD as s ->
(function [l; r] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
| _ -> assert false)
(* Divisibility *)
| `DIVISIBLE n ->
(function [a] ->
a divisble n becomes a mod n = 0
pp_print_app
safe
pvar
ppf
`EQ
[Term.T.mk_app
(Symbol.mk_symbol `MOD)
[a; Term.T.mk_const (Symbol.mk_symbol (`NUMERAL n))];
Term.T.mk_const (Symbol.mk_symbol (`NUMERAL Numeral.zero))]
| _ -> assert false)
| `SELECT _ ->
(function
| [a; i] ->
Format.fprintf ppf
"@[<hv 2>%a[%a]@]"
(pp_print_term_node safe pvar) a
(pp_print_term_node safe pvar) i
| _ -> assert false)
| `STORE ->
(function
| [a; i; v] ->
Format.fprintf ppf
"@[<hv 2>(%a with [%a] = %a)@]"
(pp_print_term_node safe pvar) a
(pp_print_term_node safe pvar) i
(pp_print_term_node safe pvar) v
| _ -> assert false)
| `UF sym as s when Symbol.is_select (Symbol.mk_symbol s) ->
pp_print_app ?as_type safe pvar ppf (`SELECT (UfSymbol.res_type_of_uf_symbol sym))
(* Unsupported functions symbols *)
| `BVCONCAT
| `DISTINCT
| `IS_INT
| `UF _ -> (function _ -> assert false)
(* Pretty-print a hashconsed term *)
let pp_print_expr_pvar ?as_type safe pvar ppf expr =
pp_print_term_node ?as_type safe pvar ppf expr
let pp_print_expr ?as_type safe ppf expr =
pp_print_expr_pvar ?as_type safe (pp_print_lustre_var safe) ppf expr
(* Pretty-print a term as an expr. *)
let pp_print_term_as_expr = pp_print_expr
let pp_print_term_as_expr_pvar = pp_print_expr_pvar
let pp_print_term_as_expr_mvar ?as_type safe map ppf expr =
pp_print_term_as_expr_pvar
?as_type safe
(fun fmt sv ->
Format.fprintf fmt "%s"
(try
StateVar.StateVarMap.find sv map
with Not_found ->
StateVar.name_of_state_var sv)
)
ppf expr
(*
(* Pretty-print a hashconsed term to the standard formatter *)
let print_expr ?as_type safe =
pp_print_expr ?as_type safe Format.std_formatter
*)
Pretty - print a typed expression
let pp_print_lustre_expr safe ppf = function
(* Same expression for initial state and following states *)
| { expr_init; expr_step; expr_type }
when Term.equal expr_init expr_step ->
pp_print_expr ~as_type:expr_type safe ppf expr_step
(* Print expression of initial state followed by expression for
following states *)
| { expr_init; expr_step; expr_type } ->
Format.fprintf ppf
"@[<hv 1>(%a@ ->@ %a)@]"
(pp_print_expr ~as_type:expr_type safe) expr_init
(pp_print_expr ~as_type:expr_type safe) expr_step
(** Pretty-print a bound or fixed annotation *)
let pp_print_bound_or_fixed ppf = function
| Bound x -> Format.fprintf ppf "@[<hv 1>(Bound %a)@]" (pp_print_expr true) x
| Fixed x -> Format.fprintf ppf "@[<hv 1>(Fixed %a)@]" (pp_print_expr true) x
| Unbound x -> Format.fprintf ppf "@[<hv 1>(Unbound %a)@]" (pp_print_expr true) x
(* ********************************************************************** *)
(* Predicates *)
(* ********************************************************************** *)
(* Return true if expression is a previous state variable *)
let has_pre_var zero_offset { expr_step } =
(* Previous state variables have negative offset *)
match Term.var_offsets_of_term expr_step with
| Some n, _ when Numeral.(n <= zero_offset + pre_offset) -> true
| _ -> false
(* Return true if there is an unguarded pre operator in the expression *)
let pre_is_unguarded { expr_init } =
(* Check if there is a pre operator in the init expression *)
match Term.var_offsets_of_term expr_init with
| None, _ -> false
| Some c, _ -> Numeral.(c < base_offset)
(* Return true if expression is a current state variable *)
let is_var_at_offset { expr_init; expr_step } (init_offset, step_offset) =
(* Term must be a free variable *)
Term.is_free_var expr_init &&
(* Get free variable of term *)
let var_init = Term.free_var_of_term expr_init in
(* Variable must be an instance of a state variable *)
Var.is_state_var_instance var_init &&
Variable must be at instant zero
Numeral.(Var.offset_of_state_var_instance var_init = init_offset) &&
(* Term must be a free variable *)
Term.is_free_var expr_step &&
(* Get free variable of term *)
let var_step = Term.free_var_of_term expr_step in
(* Variable must be an instance of a state variable *)
Var.is_state_var_instance var_step &&
Variable must be at instant zero
Numeral.(Var.offset_of_state_var_instance var_step = step_offset)(* && *)
(* StateVar.equal_state_vars *)
( )
( )
(* Return true if expression is a current state variable *)
let is_var expr = is_var_at_offset expr (base_offset, cur_offset)
(* Return true if expression is a constant state variable *)
let is_const_var { expr_init; expr_step } =
Term.is_free_var expr_init && Term.is_free_var expr_step
&& Var.is_const_state_var (Term.free_var_of_term expr_init)
&& Var.is_const_state_var (Term.free_var_of_term expr_step)
(* Return true if expression is a previous state variable *)
let is_pre_var expr = is_var_at_offset expr (pre_base_offset, pre_offset)
let is_const_expr expr =
VS.for_all Var.is_const_state_var (Term.vars_of_term expr)
(* Return true if the expression is constant *)
let is_const { expr_init; expr_step } =
is_const_expr expr_init && is_const_expr expr_step &&
Term.equal expr_init expr_step
(* ********************************************************************** *)
(* Conversion to terms *)
(* ********************************************************************** *)
Instance of state variable at instant zero
let pre_base_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
Numeral.(zero_offset |> pred)
Instance of state variable at instant zero
let base_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
zero_offset
(* Instance of state variable at current instant *)
let cur_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
zero_offset
(* Instance of state variable at previous instant *)
let pre_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
Numeral.(zero_offset |> pred)
(*
(* Term of instance of state variable at previous instant *)
let pre_base_term_of_state_var zero_offset state_var =
pre_base_var_of_state_var zero_offset state_var
|> Term.mk_var
*)
(* Term of instance of state variable at previous instant *)
let base_term_of_state_var zero_offset state_var =
base_var_of_state_var zero_offset state_var
|> Term.mk_var
(* Term of instance of state variable at current instant *)
let cur_term_of_state_var zero_offset state_var =
cur_var_of_state_var zero_offset state_var
|> Term.mk_var
(* Term of instance of state variable at previous instant *)
let pre_term_of_state_var zero_offset state_var =
pre_var_of_state_var zero_offset state_var
|> Term.mk_var
Term at instant zero
let base_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - base_offset) expr
(* Term at current instant *)
let cur_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - cur_offset) expr
(* Term at previous instant *)
let pre_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - cur_offset |> pred) expr
Term at instant zero
let base_term_of_t zero_offset { expr_init } =
base_term_of_expr zero_offset expr_init
(* Term at current instant *)
let cur_term_of_t zero_offset { expr_step } =
cur_term_of_expr zero_offset expr_step
(* Term at previous instant *)
let pre_term_of_t zero_offset { expr_step } =
pre_term_of_expr zero_offset expr_step
(* Return the state variable of a variable *)
let state_var_of_expr ({ expr_init } as expr) =
(* Initial value and step value must be identical *)
if is_var expr || is_pre_var expr then
try
(* Get free variable of term *)
let var = Term.free_var_of_term expr_init in
(* Get instance of state variable *)
Var.state_var_of_state_var_instance var
(* Fail if any of the above fails *)
with Invalid_argument _ -> raise (Invalid_argument "state_var_of_expr")
else
(* Fail if initial value is different from step value *)
raise (Invalid_argument "state_var_of_expr")
(*
(* Return the free variable of a variable *)
let var_of_expr { expr_init } =
try
Term.free_var_of_term expr_init
(* Fail if any of the above fails *)
with Invalid_argument _ -> raise (Invalid_argument "var_of_expr")
*)
(* Return the free variable of a variable *)
let var_of_expr { expr_init } =
try
Term.free_var_of_term expr_init
(* Fail if any of the above fails *)
with Invalid_argument _ -> raise (Invalid_argument "var_of_expr")
(* Return all state variables *)
let state_vars_of_expr { expr_init; expr_step } =
State variables in initial state expression
let state_vars_init = Term.state_vars_of_term expr_init in
State variables in step state expression
let state_vars_step = Term.state_vars_of_term expr_step in
(* Join sets of state variables *)
SVS.union state_vars_init state_vars_step
(* Return all state variables *)
let vars_of_expr { expr_init; expr_step } =
State variables in initial state expression
let vars_init = Term.vars_of_term expr_init in
State variables in step state expression
let vars_step = Term.vars_of_term expr_step in
(* Join sets of state variables *)
Var.VarSet.union vars_init vars_step
(* Return all state variables at the current instant in the initial
state expression *)
let base_state_vars_of_init_expr { expr_init } =
Term.state_vars_at_offset_of_term
base_offset
(base_term_of_expr base_offset expr_init)
(* Return all state variables at the current instant in the initial
state expression *)
let cur_state_vars_of_step_expr { expr_step } =
Term.state_vars_at_offset_of_term
cur_offset
(cur_term_of_expr cur_offset expr_step)
let indexes_of_state_vars_in_init sv { expr_init } =
Term.indexes_of_state_var sv expr_init
let indexes_of_state_vars_in_step sv { expr_step } =
Term.indexes_of_state_var sv expr_step
Split a list of expressions into a list of pairs of
expressions for the initial step and the transition steps ,
respectively
expressions for the initial step and the transition steps,
respectively *)
let split_expr_list list =
List.fold_left
(fun (accum_init, accum_step) { expr_init; expr_step } ->
((if expr_init == Term.t_true then
accum_init
else
expr_init :: accum_init),
(if expr_step == Term.t_true then
accum_step
else
expr_step :: accum_step)))
([], [])
list
(* ********************************************************************** *)
Generic constructors
(* ********************************************************************** *)
These constructors take as arguments functions [ eval ] and [ type_of ]
whose arity matches the arity of the constructors , where [ eval ]
applies the operator and simplifies the expression , and [ type_of ]
returns the type of the resulting expression or fails with
{ ! } .
whose arity matches the arity of the constructors, where [eval]
applies the operator and simplifies the expression, and [type_of]
returns the type of the resulting expression or fails with
{!Type_mismatch}. *)
Construct a unary expression
let mk_unary eval type_of expr =
let res_type = type_of expr.expr_type in
{ expr_init = eval expr.expr_init;
expr_step = eval expr.expr_step;
expr_type = res_type }
Construct a binary expression
let mk_binary eval type_of expr1 expr2 =
let res_type =
type_of expr1.expr_type expr2.expr_type
in
{ expr_init = eval expr1.expr_init expr2.expr_init;
expr_step = eval expr1.expr_step expr2.expr_step;
expr_type = res_type }
Construct a binary expression
let mk_ternary eval type_of expr1 expr2 expr3 =
let res_type =
type_of expr1.expr_type expr2.expr_type expr3.expr_type
in
{ expr_init = eval expr1.expr_init expr2.expr_init expr3.expr_init;
expr_step = eval expr1.expr_step expr2.expr_step expr3.expr_step;
expr_type = res_type }
(* ********************************************************************** *)
(* Constant constructors *)
(* ********************************************************************** *)
(* Boolean constant true *)
let t_true =
let expr = Term.t_true in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bool }
(* Boolean constant false *)
let t_false =
let expr = Term.t_false in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bool }
let mk_constr c t =
let expr = Term.mk_constr c in
{ expr_init = expr;
expr_step = expr;
expr_type = t }
Integer constant
let mk_int d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.mk_int_range d d }
(* Unsigned integer8 constant *)
let mk_uint8 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 8 }
(* Unsigned integer16 constant *)
let mk_uint16 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 16 }
Unsigned integer32 constant
let mk_uint32 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 32 }
(* Unsigned integer64 constant *)
let mk_uint64 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 64 }
(* Integer8 constant *)
let mk_int8 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 8 }
(* Integer16 constant *)
let mk_int16 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 16 }
(* Integer32 constant *)
let mk_int32 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 32 }
(* Integer64 constant *)
let mk_int64 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 64 }
(* Real constant *)
let mk_real f =
let expr = Term.mk_dec f in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_real }
(* Current state variable of state variable *)
let mk_var state_var =
{ expr_init = base_term_of_state_var base_offset state_var;
expr_step = cur_term_of_state_var cur_offset state_var;
expr_type = StateVar.type_of_state_var state_var }
let mk_free_var v =
let t = Term.mk_var v in
{ expr_init = t;
expr_step = t;
expr_type = Var.type_of_var v }
(* i-th index variable *)
let mk_index_var i =
let v =
Var.mk_free_var
(String.concat "."
(((I.push_index I.index_ident i) |> I.string_of_ident true)
:: I.reserved_scope)
|> HString.mk_hstring)
Type.t_int
|> Term.mk_var
in
(* create lustre expression for free variable*)
{ expr_init = v;
expr_step = v;
expr_type = Type.t_int }
let int_of_index_var { expr_init = t } =
if not (Term.is_free_var t) then raise (Invalid_argument "int_of_index_var");
let v = Term.free_var_of_term t in
let s = Var.hstring_of_free_var v |> HString.string_of_hstring in
try Scanf.sscanf s ("__index_%d%_s") (fun i -> i)
with Scanf.Scan_failure _ -> raise (Invalid_argument "int_of_index_var")
let has_q_index_expr e =
let vs = Term.vars_of_term e in
Var.VarSet.exists (fun v ->
Var.is_free_var v &&
let s = Var.hstring_of_free_var v |> HString.string_of_hstring in
try Scanf.sscanf s ("__index_%_d%_s") true
with Scanf.Scan_failure _ -> false
) vs
let has_indexes { expr_init; expr_step } =
has_q_index_expr expr_init || has_q_index_expr expr_step
(* ********************************************************************** *)
(* Type checking constructors *)
(* ********************************************************************** *)
Generic type checking functions that fail with [ Type_mismatch ] or
return a resulting type if the expressions match the required types .
return a resulting type if the expressions match the required types. *)
(* Type check for bool -> bool *)
let type_of_bool_bool = function
| t when Type.is_bool t -> Type.t_bool
| _ -> raise Type_mismatch
(* Type check for bool -> bool -> bool *)
let type_of_bool_bool_bool = function
| t when Type.is_bool t ->
(function
| t when Type.is_bool t -> Type.t_bool
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
(*
(* Type check for int -> int -> int *)
let type_of_int_int_int = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
(* Type check for real -> real -> real *)
let type_of_real_real_real = function
| t when Type.is_real t ->
(function
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
*)
(* Best int subrange for some operator. *)
let best_int_range is_div op t t' =
match Type.bounds_of_int_range t' with
| lo', hi' when (
is_div &&
Numeral.(equal lo' zero) &&
Numeral.(equal hi' zero)
) -> raise Division_by_zero
| lo', _ when (
is_div && Numeral.(equal lo' zero)
) -> Type.t_int
| _, hi' when (
is_div && Numeral.(equal hi' zero)
)-> Type.t_int
| lo', hi' ->
let lo, hi = Type.bounds_of_int_range t in
let b_0 = op lo lo' in
let bounds =
[ op hi lo' ;
op lo hi' ;
op hi hi' ]
in
Type.mk_int_range
(List.fold_left Numeral.min b_0 bounds)
(List.fold_left Numeral.max b_0 bounds)
(* Type check for int -> int -> int, real -> real -> real *)
let type_of_num_num_num ? ( is_div = false ) op t t ' =
try best_int_range is_div op t t ' with
| Invalid_argument _ - > (
match t with
| t when Type.is_int t || Type.is_int_range t - > (
match t ' with
| t when Type.is_int t || Type.is_int_range t - > Type.t_int
| _ - > raise Type_mismatch
)
| t when Type.is_real t - > (
match t ' with
| t when Type.is_real t - > Type.t_real
| _ - > raise Type_mismatch
)
| _ - > raise )
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch
)
| _ -> raise Type_mismatch
)
*)
(* Type check for int -> int -> int, real -> real -> real,
abv -> abv -> abv *)
let type_of_numOrBV_numOrBV_numOrBV ?(is_div = false) op t t' =
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_uint8 t -> (
match t' with
| t when Type.is_uint8 t -> Type.t_ubv 8
| _ -> raise Type_mismatch)
| t when Type.is_uint16 t -> (
match t' with
| t when Type.is_uint16 t -> Type.t_ubv 16
| _ -> raise Type_mismatch)
| t when Type.is_uint32 t -> (
match t' with
| t when Type.is_uint32 t -> Type.t_ubv 32
| _ -> raise Type_mismatch)
| t when Type.is_uint64 t -> (
match t' with
| t when Type.is_uint64 t -> Type.t_ubv 64
| _ -> raise Type_mismatch)
| t when Type.is_int8 t -> (
match t' with
| t when Type.is_int8 t -> Type.t_bv 8
| _ -> raise Type_mismatch)
| t when Type.is_int16 t -> (
match t' with
| t when Type.is_int16 t -> Type.t_bv 16
| _ -> raise Type_mismatch)
| t when Type.is_int32 t -> (
match t' with
| t when Type.is_int32 t -> Type.t_bv 32
| _ -> raise Type_mismatch)
| t when Type.is_int64 t -> (
match t' with
| t when Type.is_int64 t -> Type.t_bv 64
| _ -> raise Type_mismatch)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
(* Type check for int -> int -> int, real -> real -> real,
bv -> bv -> bv *)
let type_of_numOrSBV_numOrSBV_numOrSBV ?(is_div = false) op t t' =
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_int8 t -> (
match t' with
| t when Type.is_int8 t -> Type.t_bv 8
| _ -> raise Type_mismatch)
| t when Type.is_int16 t -> (
match t' with
| t when Type.is_int16 t -> Type.t_bv 16
| _ -> raise Type_mismatch)
| t when Type.is_int32 t -> (
match t' with
| t when Type.is_int32 t -> Type.t_bv 32
| _ -> raise Type_mismatch)
| t when Type.is_int64 t -> (
match t' with
| t when Type.is_int64 t -> Type.t_bv 64
| _ -> raise Type_mismatch)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
(* Type check for 'a -> 'a -> 'a *)
let type_of_a_a_a type1 type2 =
If first type is subtype of second , choose second type
if Type.check_type type1 type2 then type2
If second type is subtype of first , choose first type
else if Type.check_type type2 type1 then type1
(* Extend integer ranges if one is not a subtype of the other *)
else if Type.is_int_range type1 && Type.is_int_range type2 then Type.t_int
(* Fail if types are incompatible *)
else raise Type_mismatch
(* Type check for bv -> bv -> bv or ubv -> ubv -> ubv *)
let type_of_abv_abv_abv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| t, t' when Type.is_int8 t && Type.is_int8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_int16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_int32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_int64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
(* Type check for bv -> ubv -> bv or ubv -> ubv -> ubv *)
let type_of_abv_ubv_abv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| t, t' when Type.is_int8 t && Type.is_uint8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_uint16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_uint32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_uint64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
(*
(* Type check for ubv -> ubv -> ubv *)
let type_of_ubv_ubv_ubv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| _, _ -> raise Type_mismatch
*)
(*
(* Type check for bv -> bv -> bv *)
let type_of_bv_bv_bv t t' =
match t, t' with
| t, t' when Type.is_int8 t && Type.is_int8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_int16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_int32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_int64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
*)
(* Type check for 'a -> 'a -> bool *)
let type_of_a_a_bool type1 type2 =
if
One type must be subtype of the other
Type.check_type type1 type2
|| Type.check_type type2 type1
(* Extend integer ranges if one is not a subtype of the other *)
|| (Type.is_int_range type1 && Type.is_int_range type2)
then
Resulting type is Boolean
Type.t_bool
(* Fail if types are incompatible *)
else
raise Type_mismatch
(* Type check for int -> int -> bool, real -> real -> bool,
bv -> bv -> bool, ubv -> ubv -> bool *)
let type_of_num_num_bool = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t || Type.is_int_range t -> Type.t_bool
| _ -> raise Type_mismatch)
| t when Type.is_real t ->
(function
| t when Type.is_real t -> Type.t_bool
| _ -> raise Type_mismatch)
| t when Type.is_ubitvector t ->
(function
| t' when Type.is_ubitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
(match s1, s2 with
| 8,8 -> Type.t_bool
| 16,16 -> Type.t_bool
| 32,32 -> Type.t_bool
| 64,64 -> Type.t_bool
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t ->
(function
| t' when Type.is_bitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
(match s1, s2 with
| 8,8 -> Type.t_bool
| 16,16 -> Type.t_bool
| 32,32 -> Type.t_bool
| 64,64 -> Type.t_bool
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
(* ********************************************************************** *)
(* Evaluate unary negation
not true -> false
not false -> true
*)
let eval_not = function
| t when t == Term.t_true -> Term.t_false
| t when t == Term.t_false -> Term.t_true
| expr -> Term.mk_not expr
(* Type of unary negation
not: bool -> bool
*)
let type_of_not = type_of_bool_bool
Unary negation of expression
let mk_not expr = mk_unary eval_not type_of_not expr
(* ********************************************************************** *)
(* Evaluate unary minus
-(c) -> (-c)
-(-x) -> x
*)
let eval_uminus expr = match Term.destruct expr with
| Term.T.Const s when Symbol.is_numeral s ->
Term.mk_num Numeral.(- Symbol.numeral_of_symbol s)
| Term.T.Const s when Symbol.is_decimal s ->
Term.mk_dec Decimal.(- Symbol.decimal_of_symbol s)
| Term.T.App (s, [e]) when s == Symbol.s_minus -> e
| _ -> if (Type.is_bitvector (Term.type_of_term expr) ||
Type.is_ubitvector (Term.type_of_term expr)) then
Term.mk_bvneg expr
else
Term.mk_minus [expr]
| exception Invalid_argument _ -> Term.mk_minus [expr]
Type of unary minus
- : int - > int
- : int_range(l , u ) - > int_range(-u , -l )
- : real - > real
-: int -> int
-: int_range(l, u) -> int_range(-u, -l)
-: real -> real
*)
let type_of_uminus = function
| t when Type.is_int t -> Type.t_int
| t when Type.is_real t -> Type.t_real
| t when Type.is_int_range t ->
let (lbound, ubound) = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(- ubound) Numeral.(- lbound)
| t when Type.is_int8 t -> Type.t_bv 8
| t when Type.is_int16 t -> Type.t_bv 16
| t when Type.is_int32 t -> Type.t_bv 32
| t when Type.is_int64 t -> Type.t_bv 64
| t when Type.is_uint8 t -> Type.t_ubv 8
| t when Type.is_uint16 t -> Type.t_ubv 16
| t when Type.is_uint32 t -> Type.t_ubv 32
| t when Type.is_uint64 t -> Type.t_ubv 64
| _ -> raise Type_mismatch
Unary negation of expression
let mk_uminus expr = mk_unary eval_uminus type_of_uminus expr
(* ********************************************************************** *)
(* Evaluate bitwise negation*)
let eval_bvnot expr = Term.mk_bvnot expr
(* Type of bitwise negation *)
let type_of_bvnot = function
| t when Type.is_ubitvector t ->
let s = Type.bitvectorsize t in
(match s with
| 8 -> Type.t_ubv 8
| 16 -> Type.t_ubv 16
| 32 -> Type.t_ubv 32
| 64 -> Type.t_ubv 64
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t ->
let s = Type.bitvectorsize t in
(match s with
| 8 -> Type.t_bv 8
| 16 -> Type.t_bv 16
| 32 -> Type.t_bv 32
| 64 -> Type.t_bv 64
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
Unary negation of expression
let mk_bvnot expr = mk_unary eval_bvnot type_of_bvnot expr
(* ********************************************************************** *)
(* Evaluate conversion to integer *)
let eval_to_int expr =
let tt = Term.type_of_term expr in
if Type.is_int tt || Type.is_int_range tt then
expr
else
match Term.destruct expr with
| Term.T.Const s when Symbol.is_decimal s ->
Term.mk_num
(Numeral.of_big_int
(Decimal.to_big_int
(Symbol.decimal_of_symbol s)))
| Term.T.Const s when Symbol.is_ubv8 s ->
Term.mk_num
(Bitvector.ubv8_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv16 s ->
Term.mk_num
(Bitvector.ubv16_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv32 s ->
Term.mk_num
(Bitvector.ubv32_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv64 s ->
Term.mk_num
(Bitvector.ubv64_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv8 s ->
Term.mk_num
(Bitvector.bv8_to_num
(Symbol.bitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv16 s ->
Term.mk_num
(Bitvector.bv16_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv32 s ->
Term.mk_num
(Bitvector.bv32_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv64 s ->
Term.mk_num
(Bitvector.bv64_to_num
(Symbol.ubitvector_of_symbol s))
| x when Type.is_uint8 (Term.type_of_term (Term.construct x)) -> Term.mk_uint8_to_int expr
| x when Type.is_uint16 (Term.type_of_term (Term.construct x)) -> Term.mk_uint16_to_int expr
| x when Type.is_uint32 (Term.type_of_term (Term.construct x)) -> Term.mk_uint32_to_int expr
| x when Type.is_uint64 (Term.type_of_term (Term.construct x)) -> Term.mk_uint64_to_int expr
| x when Type.is_int8 (Term.type_of_term (Term.construct x)) -> Term.mk_int8_to_int expr
| x when Type.is_int16 (Term.type_of_term (Term.construct x)) -> Term.mk_int16_to_int expr
| x when Type.is_int32 (Term.type_of_term (Term.construct x)) -> Term.mk_int32_to_int expr
| x when Type.is_int64 (Term.type_of_term (Term.construct x)) -> Term.mk_int64_to_int expr
| _ -> Term.mk_to_int expr
| exception Invalid_argument _ ->
if Type.is_uint8 (Term.type_of_term expr) then
Term.mk_uint8_to_int expr
else if Type.is_uint16 (Term.type_of_term expr) then
Term.mk_uint16_to_int expr
else if Type.is_uint32 (Term.type_of_term expr) then
Term.mk_uint32_to_int expr
else if Type.is_uint64 (Term.type_of_term expr) then
Term.mk_uint64_to_int expr
else if Type.is_int8 (Term.type_of_term expr) then
Term.mk_int8_to_int expr
else if Type.is_int16 (Term.type_of_term expr) then
Term.mk_int16_to_int expr
else if Type.is_int32 (Term.type_of_term expr) then
Term.mk_int32_to_int expr
else if Type.is_int64 (Term.type_of_term expr) then
Term.mk_int64_to_int expr
else
Term.mk_to_int expr
(* Type of conversion to integer
int: real -> int
*)
let type_of_to_int = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_int
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int32 t || Type.is_int64 t -> Type.t_int
| _ -> raise Type_mismatch
(* Conversion to integer *)
let mk_to_int expr = mk_unary eval_to_int type_of_to_int expr
(* ********************************************************************** *)
(* Evaluate conversion to unsigned integer8 *)
let eval_to_uint8 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv8 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv8 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint8 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint8 tt) then
expr
else
Term.mk_bvextract (Numeral.of_int 7) (Numeral.of_int 0) expr
else
raise Type_mismatch
(* Type of conversion to unsigned integer8
int: real -> uint8
*)
let type_of_to_uint8 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint8 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 8
| t when Type.is_uint16 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_ubv 8
| _ -> raise Type_mismatch
(* Conversion to unsigned integer8 *)
let mk_to_uint8 expr = mk_unary eval_to_uint8 type_of_to_uint8 expr
(* ********************************************************************** *)
(* Evaluate conversion to unsigned integer16 *)
let eval_to_uint16 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv16 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv16 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint16 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint16 tt) then
expr
else if (Type.is_uint8 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 8)) expr
else
Term.mk_bvextract (Numeral.of_int 15) (Numeral.of_int 0) expr
else
raise Type_mismatch
(* Type of conversion to unsigned integer16
int: real -> uint16
*)
let type_of_to_uint16 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint16 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 16
| t when Type.is_uint8 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_ubv 16
| _ -> raise Type_mismatch
(* Conversion to unsigned integer16 *)
let mk_to_uint16 expr = mk_unary eval_to_uint16 type_of_to_uint16 expr
(* ********************************************************************** *)
Evaluate conversion to unsigned integer32
let eval_to_uint32 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv32 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv32 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint32 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint32 tt) then
expr
else if (Type.is_uint8 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 24)) expr
else if (Type.is_uint16 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 16)) expr
else
Term.mk_bvextract (Numeral.of_int 31) (Numeral.of_int 0) expr
let n = Term.mk_bv2nat expr in
Term.mk_to_uint32 n
Term.mk_to_uint32 n*)
else
raise Type_mismatch
Type of conversion to unsigned integer32
int : real - > uint32
int: real -> uint32
*)
let type_of_to_uint32 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint32 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 32
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint64 t -> Type.t_ubv 32
| _ -> raise Type_mismatch
Conversion to unsigned integer32
let mk_to_uint32 expr = mk_unary eval_to_uint32 type_of_to_uint32 expr
(* ********************************************************************** *)
(* Evaluate conversion to unsigned integer64 *)
let eval_to_uint64 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv64 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv64 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint64 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint64 tt) then
expr
else if (Type.is_uint32 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 32)) expr
else if (Type.is_uint16 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 48)) expr
else
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 56)) expr
else
raise Type_mismatch
Type of conversion to unsigned integer64
int : real - > int64
int: real -> int64
*)
let type_of_to_uint64 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint64 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 64
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint32 t -> Type.t_ubv 64
| _ -> raise Type_mismatch
(* Conversion to unsigned integer64 *)
let mk_to_uint64 expr = mk_unary eval_to_uint64 type_of_to_uint64 expr
(* ********************************************************************** *)
(* Evaluate conversion to integer8 *)
let eval_to_int8 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv8 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv8 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int8 expr
else if (Type.is_bitvector tt) then
if (Type.is_int8 tt) then
expr
else
Term.mk_bvextract (Numeral.of_int 7) (Numeral.of_int 0) expr
else
raise Type_mismatch
(* Type of conversion to integer8
int: real -> int8
*)
let type_of_to_int8 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int8 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 8
| t when Type.is_int16 t || Type.is_int32 t || Type.is_int64 t -> Type.t_bv 8
| _ -> raise Type_mismatch
Conversion to integer8
let mk_to_int8 expr = mk_unary eval_to_int8 type_of_to_int8 expr
(* ********************************************************************** *)
(* Evaluate conversion to integer16 *)
let eval_to_int16 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv16 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv16 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int16 expr
else if (Type.is_bitvector tt) then
if (Type.is_int16 tt) then
expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 8) expr
else
Term.mk_bvextract (Numeral.of_int 15) (Numeral.of_int 0) expr
else
raise Type_mismatch
(* Type of conversion to integer16
int: real -> int16
*)
let type_of_to_int16 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int16 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 16
| t when Type.is_int8 t || Type.is_int32 t || Type.is_int64 t -> Type.t_bv 16
| _ -> raise Type_mismatch
(* Conversion to integer16 *)
let mk_to_int16 expr = mk_unary eval_to_int16 type_of_to_int16 expr
(* ********************************************************************** *)
Evaluate conversion to integer32
let eval_to_int32 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv32 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv32 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int32 expr
else if (Type.is_bitvector tt) then
if (Type.is_int32 tt) then
expr
else if (Type.is_int64 tt) then
Term.mk_bvextract (Numeral.of_int 31) (Numeral.of_int 0) expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 24) expr
else
Term.mk_bvsignext (Numeral.of_int 16) expr
else
raise Type_mismatch
Type of conversion to integer32
int : real - > int32
int: real -> int32
*)
let type_of_to_int32 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int32 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 32
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int64 t -> Type.t_bv 32
| _ -> raise Type_mismatch
Conversion to integer32
let mk_to_int32 expr = mk_unary eval_to_int32 type_of_to_int32 expr
(* ********************************************************************** *)
(* Evaluate conversion to integer64 *)
let eval_to_int64 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv64 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv64 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int64 expr
else if (Type.is_bitvector tt) then
if (Type.is_int64 tt) then
expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 56) expr
else if (Type.is_int16 tt) then
Term.mk_bvsignext (Numeral.of_int 48) expr
else
Term.mk_bvsignext (Numeral.of_int 32) expr
else
raise Type_mismatch
Type of conversion to integer64
int : real - > int64
int: real -> int64
*)
let type_of_to_int64 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int64 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 64
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int32 t -> Type.t_bv 64
| _ -> raise Type_mismatch
(* Conversion to integer64 *)
let mk_to_int64 expr = mk_unary eval_to_int64 type_of_to_int64 expr
(* ********************************************************************** *)
(* Evaluate conversion to real *)
let eval_to_real expr =
let tt = Term.type_of_term expr in
if Type.is_real tt then
expr
else
match Term.destruct expr with
| Term.T.Const s when Symbol.is_numeral s ->
Term.mk_dec
(Decimal.of_big_int
(Numeral.to_big_int
(Symbol.numeral_of_symbol s)))
| _ -> Term.mk_to_real expr
| exception Invalid_argument _ -> Term.mk_to_real expr
(* Type of conversion to real
real: int -> real
*)
let type_of_to_real = function
| t when Type.is_int t || Type.is_int_range t -> Type.t_real
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch
(* Conversion to integer *)
let mk_to_real expr = mk_unary eval_to_real type_of_to_real expr
(* ********************************************************************** *)
(* Evaluate Boolean conjunction
true and e2 -> e2
false and e2 -> false
e1 and true -> e1
e1 and false -> false *)
let eval_and = function
| t when t == Term.t_true -> (function expr2 -> expr2)
| t when t == Term.t_false -> (function _ -> Term.t_false)
| expr1 ->
(function
| t when t == Term.t_true -> expr1
| t when t == Term.t_false -> Term.t_false
| expr2 -> Term.mk_and [expr1; expr2])
(* Type of Boolean conjunction
and: bool -> bool -> bool *)
let type_of_and = type_of_bool_bool_bool
Boolean conjunction
let mk_and expr1 expr2 = mk_binary eval_and type_of_and expr1 expr2
(* n-ary Boolean conjunction *)
let mk_and_n = function
| [] -> t_true
| h :: [] -> h
| h :: tl -> List.fold_left mk_and h tl
(* ********************************************************************** *)
(* Evaluate Boolean disjunction
true or e2 -> true
false or e2 -> e2
e1 or true -> true
e1 or false -> e1 *)
let eval_or = function
| t when t == Term.t_true -> (function _ -> Term.t_true)
| t when t == Term.t_false -> (function expr2 -> expr2)
| expr1 ->
(function
| t when t == Term.t_true -> Term.t_true
| t when t == Term.t_false -> expr1
| expr2 -> Term.mk_or [expr1; expr2])
(* Type of Boolean disjunction
or: bool -> bool -> bool *)
let type_of_or = type_of_bool_bool_bool
(* Boolean disjunction *)
let mk_or expr1 expr2 = mk_binary eval_or type_of_or expr1 expr2
(* n-ary Boolean disjunction *)
let mk_or_n = function
| [] -> t_true
| h :: [] -> h
| h :: tl -> List.fold_left mk_or h tl
(* ********************************************************************** *)
(* Evaluate Boolean exclusive disjunction
true xor e2 -> not e2
false xor e2 -> e2
e1 xor true -> not e1
e1 xor false -> e1 *)
let eval_xor = function
| t when t == Term.t_true -> (function expr2 -> eval_not expr2)
| t when t == Term.t_false -> (function expr2 -> expr2)
| expr1 ->
(function
| t when t == Term.t_true -> eval_not expr1
| t when t == Term.t_false -> expr1
| expr2 -> Term.mk_xor [expr1; expr2])
Type of Boolean exclusive disjunction
xor : bool - > bool - > bool
xor: bool -> bool -> bool *)
let type_of_xor = type_of_bool_bool_bool
Boolean exclusive disjunction
let mk_xor expr1 expr2 = mk_binary eval_xor type_of_xor expr1 expr2
(* ********************************************************************** *)
(* Evaluate Boolean implication
true => e2 -> e2
false => e2 -> true
e1 => true -> true
e1 => false -> not e1 *)
let eval_impl = function
| t when t == Term.t_true -> (function expr2 -> expr2)
| t when t == Term.t_false -> (function _ -> Term.t_true)
| expr1 ->
(function
| t when t == Term.t_true -> Term.t_true
| t when t == Term.t_false -> eval_not expr1
| expr2 -> Term.mk_implies [expr1; expr2])
(* Type of Boolean implication
=>: bool -> bool -> bool *)
let type_of_impl = type_of_bool_bool_bool
(* Boolean implication *)
let mk_impl expr1 expr2 = mk_binary eval_impl type_of_impl expr1 expr2
(* ********************************************************************** *)
let mk_let bindings expr =
{
expr_init = Term.mk_let bindings expr.expr_init;
expr_step = Term.mk_let bindings expr.expr_step;
expr_type = expr.expr_type;
}
(* ********************************************************************** *)
let apply_subst sigma expr =
{
expr_init = Term.apply_subst sigma expr.expr_init;
expr_step = Term.apply_subst sigma expr.expr_step;
expr_type = expr.expr_type;
}
(* ********************************************************************** *)
(* Evaluate universal quantification *)
let eval_forall vars t = match vars, t with
| [], _ -> Term.t_true
| _, t when t == Term.t_true -> Term.t_true
| _, t when t == Term.t_false -> Term.t_false
| _ -> Term.mk_forall vars t
let type_of_forall = type_of_bool_bool
Universal quantification
let mk_forall vars expr =
mk_unary (eval_forall vars) type_of_forall expr
(* ********************************************************************** *)
(* Evaluate existential quantification *)
let eval_exists vars t = match vars, t with
| [], _ -> Term.t_false
| _, t when t == Term.t_true -> Term.t_true
| _, t when t == Term.t_false -> Term.t_false
| _ -> Term.mk_exists vars t
let type_of_exists = type_of_bool_bool
(* Existential quantification*)
let mk_exists vars expr = mk_unary (eval_exists vars) type_of_exists expr
(* ********************************************************************** *)
(* Evaluate integer modulus *)
let eval_mod expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 mod
Symbol.numeral_of_symbol c2)
| _ -> (if Type.is_ubitvector (Term.type_of_term expr1) then
Term.mk_bvurem [expr1; expr2]
else if Type.is_bitvector (Term.type_of_term expr1) then
Term.mk_bvsrem [expr1; expr2]
else
Term.mk_mod expr1 expr2)
| exception Invalid_argument _ -> Term.mk_mod expr1 expr2
Type of integer modulus
If j is bounded by [ l , u ] , then the result of i mod j is bounded by
[ 0 , ( max(|l| , |u| ) - 1 ) ] .
mod : int - > int - > int
If j is bounded by [l, u], then the result of i mod j is bounded by
[0, (max(|l|, |u|) - 1)].
mod: int -> int -> int *)
let type_of_mod = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t -> Type.t_int
| t when Type.is_int_range t ->
let l, u = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.zero Numeral.(pred (max (abs l) (abs u)))
| _ -> raise Type_mismatch)
| t1 when Type.is_ubitvector t1 ->
(function
| t2 when Type.is_ubitvector t2 ->
let s1 = Type.bitvectorsize t1 in
let s2 = Type.bitvectorsize t2 in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_ubv 8
| 16, 16 -> Type.t_ubv 16
| 32, 32 -> Type.t_ubv 32
| 64, 64 -> Type.t_ubv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t1 when Type.is_bitvector t1 ->
(function
| t2 when Type.is_bitvector t2 ->
let s1 = Type.bitvectorsize t1 in
let s2 = Type.bitvectorsize t2 in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_bv 8
| 16, 16 -> Type.t_bv 16
| 32, 32 -> Type.t_bv 32
| 64, 64 -> Type.t_bv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
Integer modulus
let mk_mod expr1 expr2 = mk_binary eval_mod type_of_mod expr1 expr2
(* ********************************************************************** *)
(* Evaluate subtraction *)
let eval_minus expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 -
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 -
Symbol.decimal_of_symbol c2)
| _ -> (if ((Type.is_bitvector (Term.type_of_term expr1))
|| (Type.is_ubitvector (Term.type_of_term expr1))) then
Term.mk_bvsub [expr1; expr2]
else
Term.mk_minus [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_minus [expr1; expr2]
Type of subtraction
If both arguments are bounded , the difference is bounded by the
difference of the lower bound of the first argument and the upper
bound of the second argument and the difference of the upper bound
of the first argument and the lower bound of the second argument .
- : int - > int - > int
real - > real - > real
If both arguments are bounded, the difference is bounded by the
difference of the lower bound of the first argument and the upper
bound of the second argument and the difference of the upper bound
of the first argument and the lower bound of the second argument.
-: int -> int -> int
real -> real -> real *)
let type_of_minus = function
| t when Type.is_int_range t ->
(function
| s when Type.is_int_range s ->
let l1, u1 = Type.bounds_of_int_range t in
let l2, u2 = Type.bounds_of_int_range s in
Type.mk_int_range Numeral.(l1 - u2) Numeral.(u1 - l2)
| s -> type_of_numOrSBV_numOrSBV_numOrSBV Numeral.sub t s)
| t -> type_of_numOrBV_numOrBV_numOrBV Numeral.sub t
(* Subtraction *)
let mk_minus expr1 expr2 = mk_binary eval_minus type_of_minus expr1 expr2
(* ********************************************************************** *)
(* Evaluate addition *)
let eval_plus expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 +
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 +
Symbol.decimal_of_symbol c2)
| _ -> (if (((Type.is_bitvector (Term.type_of_term expr1))
&& (Type.is_bitvector (Term.type_of_term expr2)))
||
((Type.is_ubitvector (Term.type_of_term expr1))
&& (Type.is_ubitvector (Term.type_of_term expr1)))) then
Term.mk_bvadd [expr1; expr2]
else
Term.mk_plus [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_plus [expr1; expr2]
(* Type of addition
If both summands are bounded, the sum is bounded by the sum of the
lower bound and the sum of the upper bounds.
+: int -> int -> int
real -> real -> real *)
let type_of_plus = function
| t when Type.is_int_range t ->
(function
| s when Type.is_int_range s ->
let l1, u1 = Type.bounds_of_int_range t in
let l2, u2 = Type.bounds_of_int_range s in
Type.mk_int_range Numeral.(l1 + l2) Numeral.(u1 + u2)
| s -> type_of_numOrBV_numOrBV_numOrBV Numeral.add t s)
| t -> type_of_numOrBV_numOrBV_numOrBV Numeral.add t
(* Addition *)
let mk_plus expr1 expr2 = mk_binary eval_plus type_of_plus expr1 expr2
(* ********************************************************************** *)
(* Evaluate real division *)
let eval_div expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 ->
if Symbol.is_decimal c1 && Symbol.is_decimal c2 then
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 /
Symbol.decimal_of_symbol c2)
else (
assert (Symbol.is_numeral c1 && Symbol.is_numeral c2);
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 /
Symbol.numeral_of_symbol c2)
)
| _ ->
let tt = Term.type_of_term expr1 in
if Type.is_real tt then (
Term.mk_div [expr1; expr2]
)
else if Type.is_ubitvector (Term.type_of_term expr1) then (
Term.mk_bvudiv [expr1; expr2]
)
else if Type.is_bitvector (Term.type_of_term expr1) then (
Term.mk_bvsdiv [expr1; expr2]
)
else (
Term.mk_intdiv [expr1; expr2]
)
| exception Invalid_argument _ -> Term.mk_div [expr1; expr2]
(* Type of real division
/: real -> real -> real
When the operator is applied to integer and machine integer arguments,
its semantics is the same as integer division (div)
*)
let type_of_div = type_of_numOrBV_numOrBV_numOrBV ~is_div:true Numeral.div
(* Real division *)
let mk_div expr1 expr2 = mk_binary eval_div type_of_div expr1 expr2
(* ********************************************************************** *)
(* Evaluate multiplication *)
let eval_times expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 *
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 *
Symbol.decimal_of_symbol c2)
| _ -> (if (Type.is_bitvector (Term.type_of_term expr1) ||
Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvmul [expr1; expr2]
else
Term.mk_times [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_times [expr1; expr2]
(* Type of multiplication
*: int -> int -> int
real -> real -> real *)
let type_of_times = type_of_numOrBV_numOrBV_numOrBV Numeral.mult
(* Multiplication *)
let mk_times expr1 expr2 = mk_binary eval_times type_of_times expr1 expr2
(* ********************************************************************** *)
(* Evaluate integer division *)
let eval_intdiv expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 /
Symbol.numeral_of_symbol c2)
| _ -> (if Type.is_ubitvector (Term.type_of_term expr1) then
Term.mk_bvudiv [expr1; expr2]
else if Type.is_bitvector (Term.type_of_term expr1) then
Term.mk_bvsdiv [expr1; expr2]
else
Term.mk_intdiv [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_intdiv [expr1; expr2]
(* Type of integer division
div: int -> int -> int *)
let type_of_intdiv t t' =
try best_int_range true Numeral.div t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_ubitvector t -> (
match t' with
| t' when Type.is_ubitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_ubv 8
| 16, 16 -> Type.t_ubv 16
| 32, 32 -> Type.t_ubv 32
| 64, 64 -> Type.t_ubv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t -> (
match t' with
| t' when Type.is_bitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_bv 8
| 16, 16 -> Type.t_bv 16
| 32, 32 -> Type.t_bv 32
| 64, 64 -> Type.t_bv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
)
Integer division
let mk_intdiv expr1 expr2 = mk_binary eval_intdiv type_of_intdiv expr1 expr2
(* ********************************************************************** *)
(* Evaluate bitvector conjunction *)
let eval_bvand expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| _ -> Term.mk_bvand [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_bvand [expr1; expr2]
(* Type of bitvector conjunction*)
let type_of_bvand = type_of_abv_abv_abv
Bitvector conjunction
let mk_bvand expr1 expr2 = mk_binary eval_bvand type_of_bvand expr1 expr2
(* ********************************************************************** *)
(* Evaluate bitvector disjunction *)
let eval_bvor expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| _ -> Term.mk_bvor [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_bvor [expr1; expr2]
(* Type of bitvector disjunction *)
let type_of_bvor = type_of_abv_abv_abv
Bitvector disjunction
let mk_bvor expr1 expr2 = mk_binary eval_bvor type_of_bvor expr1 expr2
(* ********************************************************************** *)
(* Evaluate bitvector left shift *)
let eval_bvshl expr1 expr2 =
if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))) then
Term.mk_bvshl [expr1; expr2]
else
match Term.destruct expr1, Term.destruct expr2 with
| _ -> raise NonConstantShiftOperand
| exception Invalid_argument _ -> Term.mk_bvshl [expr1; expr2]
(* Type of bitvector left shift *)
let type_of_bvshl = type_of_abv_ubv_abv
Bitvector left shift
let mk_bvshl expr1 expr2 = mk_binary eval_bvshl type_of_bvshl expr1 expr2
(* ********************************************************************** *)
(* Evaluate bitvector (logical or arithmetic) right shift *)
let eval_bvshr expr1 expr2 =
if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))
&& (Type.is_bitvector (Term.type_of_term expr1))) then
Term.mk_bvashr [expr1; expr2]
else if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))
&& (Type.is_ubitvector (Term.type_of_term expr1))) then
Term.mk_bvlshr [expr1; expr2]
else
match Term.destruct expr1, Term.destruct expr2 with
| _ -> raise NonConstantShiftOperand
| exception Invalid_argument _ -> Term.mk_bvshl [expr1; expr2]
(* Type of bitvector logical right shift *)
let type_of_bvshr = type_of_abv_ubv_abv
Bitvector logical right shift
let mk_bvshr expr1 expr2 = mk_binary eval_bvshr type_of_bvshr expr1 expr2
(* ********************************************************************** *)
let has_pre_vars t =
Term.state_vars_at_offset_of_term (Numeral.of_int (-1)) t
|> StateVar.StateVarSet.is_empty
|> not
(* Evaluate equality *)
let eval_eq expr1 expr2 = match expr1, expr2 with
(* true = e2 -> e2 *)
| t, _ when t == Term.t_true -> expr2
(* false = e2 -> not e2 *)
| t, _ when t == Term.t_false -> eval_not expr2
(* e1 = true -> e1 *)
| _, t when t == Term.t_true -> expr1
(* e1 = false -> not e1 *)
| _, t when t == Term.t_false -> eval_not expr1
(* e = e -> true and e has no pre *)
| _ when Term.equal expr1 expr2
&& not (has_pre_vars expr1) && not (has_pre_vars expr2) ->
Term.t_true
| _ ->
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 =
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 =
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ -> Term.mk_eq [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_eq [expr1; expr2]
(* Type of equality
=: 'a -> 'a -> bool *)
let type_of_eq = type_of_a_a_bool
(* Equality *)
let mk_eq expr1 expr2 = mk_binary eval_eq type_of_eq expr1 expr2
(* ********************************************************************** *)
(* Evaluate disequality *)
let eval_neq expr1 expr2 = eval_not (eval_eq expr1 expr2)
(* Type of disequality
<>: 'a -> 'a -> bool *)
let type_of_neq = type_of_a_a_bool
(* Disequality *)
let mk_neq expr1 expr2 = mk_binary eval_neq type_of_neq expr1 expr2
(* ********************************************************************** *)
(* Evaluate inequality *)
let eval_lte expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 <=
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 <=
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(* Bitvector comparisons are simplified in the simplify module *)
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvule [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvsle [expr1; expr2]
else
Term.mk_leq [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_leq [expr1; expr2]
(* Type of inequality
<=: int -> int -> bool
real -> real -> bool *)
let type_of_lte = type_of_num_num_bool
(* Disequality *)
let mk_lte expr1 expr2 = mk_binary eval_lte type_of_lte expr1 expr2
(* ********************************************************************** *)
(* Evaluate inequality *)
let eval_lt expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 <
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 <
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(* Bitvector comparisons are simplified in the simplify module *)
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvult [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvslt [expr1; expr2]
else
Term.mk_lt [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_lt [expr1; expr2]
(* Type of inequality
<: int -> int -> bool
real -> real -> bool *)
let type_of_lt = type_of_num_num_bool
(* Disequality *)
let mk_lt expr1 expr2 = mk_binary eval_lt type_of_lt expr1 expr2
(* ********************************************************************** *)
(* Evaluate inequality *)
let eval_gte expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 >=
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 >=
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(* Bitvector comparisons are simplified in the simplify module *)
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvuge [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvsge [expr1; expr2]
else
Term.mk_geq [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_geq [expr1; expr2]
(* Type of inequality
>=: int -> int -> bool
real -> real -> bool *)
let type_of_gte = type_of_num_num_bool
(* Disequality *)
let mk_gte expr1 expr2 = mk_binary eval_gte type_of_gte expr1 expr2
(* ********************************************************************** *)
(* Evaluate inequality *)
let eval_gt expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 >
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 >
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(* Bitvector comparisons are simplified in the simplify module *)
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
if ( Bitvector.ugt ( Term.bitvector_of_term expr1 ) ( Term.bitvector_of_term expr2 ) ) then
Term.t_true
else
Term.t_false
Term.t_true
else
Term.t_false*)
Term.mk_bvugt [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
if ( Bitvector.gt ( Term.bitvector_of_term expr1 ) ( Term.bitvector_of_term expr2 ) ) then
Term.t_true
else
Term.t_false
Term.t_true
else
Term.t_false*)
Term.mk_bvsgt [expr1; expr2]
else
Term.mk_gt [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_gt [expr1; expr2]
(* Type of inequality
>=: int -> int -> bool
real -> real -> bool *)
let type_of_gt = type_of_num_num_bool
(* Disequality *)
let mk_gt expr1 expr2 = mk_binary eval_gt type_of_gt expr1 expr2
(* ********************************************************************** *)
(* Evaluate if-then-else *)
let eval_ite = function
| t when t == Term.t_true -> (function expr2 -> (function _ -> expr2))
| t when t == Term.t_false -> (function _ -> (function expr3 -> expr3))
| expr1 ->
(function expr2 ->
(function expr3 ->
if Term.equal expr2 expr3 then
expr2
else
(Term.mk_ite expr1 expr2 expr3)))
Type of if - then - else
If both the second and the third argument are bounded , the result
is bounded by the smaller of the two lower bound and the greater of
the upper bounds .
ite : bool - > ' a - > ' a - > ' a
If both the second and the third argument are bounded, the result
is bounded by the smaller of the two lower bound and the greater of
the upper bounds.
ite: bool -> 'a -> 'a -> 'a *)
let type_of_ite = function
| t when t = Type.t_bool ->
(function type2 -> function type3 ->
If first type is subtype of second , choose second type
if Type.check_type type2 type3 then type3 else
If second type is subtype of first , choose first type
if Type.check_type type3 type2 then type2 else
(* Extend integer ranges if one is not a subtype of the other *)
(match type2, type3 with
| s, t
when (Type.is_int_range s && Type.is_int t) ||
(Type.is_int s && Type.is_int_range t) -> Type.t_int
| s, t
when (Type.is_int_range s && Type.is_int_range t) ->
let l1, u1 = Type.bounds_of_int_range s in
let l2, u2 = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(min l1 l2) Numeral.(max u1 u2)
| _ -> raise Type_mismatch))
| _ -> (function _ -> function _ -> raise Type_mismatch)
(* If-then-else *)
let mk_ite expr1 expr2 expr3 =
mk_ternary eval_ite type_of_ite expr1 expr2 expr3
(* ********************************************************************** *)
Type of - >
If both the arguments are bounded , the result is bounded by the
smaller of the two lower bound and the greater of the upper bounds .
- > : ' a - > ' a - > ' a
If both the arguments are bounded, the result is bounded by the
smaller of the two lower bound and the greater of the upper bounds.
->: 'a -> 'a -> 'a *)
let type_of_arrow type1 type2 =
(* Extend integer ranges if one is not a subtype of the other *)
(match type1, type2 with
| s, t
when (Type.is_int_range s && Type.is_int_range t) ->
let l1, u1 = Type.bounds_of_int_range s in
let l2, u2 = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(min l1 l2) Numeral.(max u1 u2)
| _ -> type_of_a_a_a type1 type2)
(* Followed by expression *)
let mk_arrow expr1 expr2 =
(* Types of expressions must be compatible *)
let res_type =
type_of_arrow expr1.expr_type expr2.expr_type
in
{ expr_init = expr1.expr_init;
expr_step = expr2.expr_step;
expr_type = res_type }
(* ********************************************************************** *)
(* Pre expression *)
We do n't need to abstract the RHS because the AST normalization pass
already has .
already has. *)
let mk_pre ({ expr_init; expr_step } as expr) =
if Term.equal expr_init expr_step then
match expr_init with
(* Expression is a constant not part of an unguarded pre expression *)
| t when (t == Term.t_true
|| t == Term.t_false
|| (Term.is_free_var t && Term.free_var_of_term t |> Var.is_const_state_var)
|| (match Term.destruct t with
| Term.T.Const c1 when Symbol.is_numeral c1 || Symbol.is_decimal c1 -> true
| _ -> false))
-> expr
(* Expression is a variable at the current instant not part of an unguarded
pre expression *)
| t when Term.is_free_var t
&& Term.free_var_of_term t |> Var.is_state_var_instance
&& Numeral.(Var.offset_of_state_var_instance (Term.free_var_of_term t) = base_offset) ->
let pt = Term.bump_state Numeral.(- one) t in
{ expr with expr_init = pt; expr_step = pt }
(* Expression is not a variable at the current instant or a constant:
abstract *)
(* AST Normalization makes this situation impossible *)
| _ -> assert false
(* Stream is of the form: a -> b, abstract*)
(* AST Normalization makes this situation impossible *)
else assert false
let mk_pre_with_context mk_abs_for_expr mk_lhs_term ctx unguarded
({ expr_init; expr_step; expr_type } as expr) =
(* When simplifications fails, simply abstract with a new state variable,
i.e., create an internal new memory. *)
let abs_pre () =
let expr_type = Type.generalize expr_type in
let expr = { expr with expr_type } in
(* Fresh state variable for identifier *)
let abs, ctx = mk_abs_for_expr ctx expr in
(* Abstraction at previous instant *)
let abs_t = mk_lhs_term abs in
{ expr_init = abs_t;
expr_step = abs_t;
expr_type }, ctx
in
(* Stream is the same in the initial state and step (e -> e) *)
if not unguarded &&
Term.equal expr_init expr_step then
match expr_init with
(* Expression is a constant not part of an unguarded pre expression *)
| t when
(t == Term.t_true ||
t == Term.t_false ||
(Term.is_free_var t &&
Term.free_var_of_term t |> Var.is_const_state_var) ||
(match Term.destruct t with
| Term.T.Const c1 when
Symbol.is_numeral c1 || Symbol.is_decimal c1 -> true
| _ -> false)) ->
expr, ctx
(* Expression is a variable at the current instant not part of an unguarded
pre expression *)
| t when Term.is_free_var t &&
Term.free_var_of_term t |> Var.is_state_var_instance &&
Numeral.(Var.offset_of_state_var_instance (Term.free_var_of_term t) =
base_offset) ->
let pt = Term.bump_state Numeral.(- one) t in
{ expr with expr_init = pt; expr_step = pt }, ctx
(* Expression is not a variable at the current instant or a constant:
abstract *)
| _ -> abs_pre ()
else (* Stream is of the form: a -> b, abstract*)
abs_pre ()
(* ********************************************************************** *)
(* Evaluate select from array
Nothing to simplify here *)
let eval_select = Term.mk_select
(* Type of A[k]
A[k]: array 'a 'b -> 'a -> 'b *)
let type_of_select = function
First argument must be an array type
| s when Type.is_array s ->
(function t ->
Second argument must match index type of array
if Type.check_type (Type.index_type_of_array s) t then
(* Return type of array elements *)
Type.elem_type_of_array s
else
(* Type of indexes do not match*)
raise Type_mismatch)
(* Not an array type *)
| _ -> raise Type_mismatch
(* Select from an array *)
let mk_select expr1 expr2 =
(* Types of expressions must be compatible *)
mk_binary eval_select type_of_select expr1 expr2
let mk_array expr1 expr2 =
(* Types of expressions must be compatible *)
let type_of_array t1 t2 = Type.mk_array t1 t2 in
mk_binary (fun x _ -> x) type_of_array expr1 expr2
(* ********************************************************************** *)
(* Evaluate store from array
Nothing to simplify here *)
let eval_store = Term.mk_store
let type_of_store = function
First argument must be an array type
| s when Type.is_array s ->
(fun i v ->
Second argument must match index type of array
if Type.check_type i (Type.index_type_of_array s) &&
Type.check_type (Type.elem_type_of_array s) v
then
(* Return type of array *)
s
else
(* Type of indexes do not match*)
raise Type_mismatch)
(* Not an array type *)
| _ ->
raise Type_mismatch
(* Store from an array *)
let mk_store expr1 expr2 expr3 =
Format.eprintf " mk_store % a:%a [ % a , % a ] % a:%a % a:%a@. "
( pp_print_lustre_expr false ) expr1
Type.pp_print_type ( type_of_lustre_expr expr1 )
(* Type.pp_print_type (Type.index_type_of_array (type_of_lustre_expr expr1)) *)
Type.pp_print_type ( Type.elem_type_of_array ( type_of_lustre_expr expr1 ) )
( pp_print_lustre_expr false ) expr2
Type.pp_print_type ( type_of_lustre_expr expr2 )
(* (pp_print_lustre_expr false) expr3 *)
Type.pp_print_type ( type_of_lustre_expr expr3 ) ;
(* Types of expressions must be compatible *)
mk_ternary eval_store type_of_store expr1 expr2 expr3
let is_store e = Term.is_store e.expr_init && Term.is_store e.expr_step
let is_select e = Term.is_select e.expr_init && Term.is_select e.expr_step
let is_select_array_var e =
is_select e &&
try
ignore (Term.indexes_and_var_of_select e.expr_init);
ignore (Term.indexes_and_var_of_select e.expr_step);
true
with Invalid_argument _ -> false
let var_of_array_select e =
let v1, _ = Term.indexes_and_var_of_select e.expr_init in
let v2, _ = Term.indexes_and_var_of_select e.expr_step in
if not (Var.equal_vars v1 v2) then invalid_arg ("var_of_array_select");
v1
(* For an array select expression, get variable and list of indexes.
* XXX: We could implement var_of_array_select in terms of this, but this
* is stricter than var_of_array_select and will fail on different
* indexes in init vs step. Maybe that should be the case anyway? *)
let indexes_and_var_of_array_select e =
let v1, ixes1 = Term.indexes_and_var_of_select e.expr_init in
let v2, ixes2 = Term.indexes_and_var_of_select e.expr_step in
if not (Var.equal_vars v1 v2) then
invalid_arg ("indexes_and_var_of_array_select.var");
if not (List.for_all2 Term.equal ixes1 ixes2) then
invalid_arg ("indexes_and_var_of_array_select.indexes");
(v1, ixes1)
(* ********************************************************************** *)
(* Apply let binding for state variable at current instant to
expression *)
let mk_let_cur substs ({ expr_init; expr_step } as expr) =
(* Split substitutions for initial state and step state *)
let substs_init, substs_step =
let i, s =
List.fold_left
(fun (substs_init, substs_step) (sv, { expr_init; expr_step }) ->
((base_var_of_state_var base_offset sv, expr_init) :: substs_init,
(cur_var_of_state_var cur_offset sv, expr_step) :: substs_step))
([], [])
substs
in
List.rev i, List.rev s
in
(* Apply substitutions separately *)
{ expr with
expr_init = Term.mk_let substs_init expr_init;
expr_step = Term.mk_let substs_step expr_step }
(* Apply let binding for state variable at previous instant to
expression *)
let mk_let_pre substs ({ expr_init; expr_step } as expr) =
(* Split substitutions for initial state and step state *)
let substs_init, substs_step =
let i, s =
List.fold_left
(fun (substs_init, substs_step) (sv, { expr_init; expr_step }) ->
((pre_base_var_of_state_var base_offset sv, expr_init) :: substs_init,
(pre_var_of_state_var cur_offset sv, expr_step) :: substs_step))
([], [])
substs
in
List.rev i, List.rev s
in
let subst_has_arrays =
List.exists (fun (v, _) -> Var.type_of_var v |> Type.is_array) in
let expr_init =
if subst_has_arrays substs_init then Term.apply_subst substs_init expr_init
else Term.mk_let substs_init expr_init in
let expr_step =
if subst_has_arrays substs_step then Term.apply_subst substs_step expr_step
else Term.mk_let substs_step expr_step in
(* Apply substitutions separately *)
{ expr with expr_init; expr_step}
(* ********************************************************************** *)
(* Return expression of a numeral *)
let mk_int_expr n = Term.mk_num n
let mk_of_expr ?as_type expr =
let expr_type = match as_type with
| Some ty -> ty
| None -> Term.type_of_term expr
in
{ expr_init = expr;
expr_step = expr;
expr_type }
let is_numeral = Term.is_numeral
let numeral_of_expr = Term.numeral_of_term
let unsafe_term_of_expr e = (e : Term.t)
let unsafe_expr_of_term t = t
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
| null | https://raw.githubusercontent.com/kind2-mc/kind2/85f11c69378681d5c8b4294308e23024f348d10d/src/lustre/lustreExpr.ml | ocaml | Abbreviations
Exceptions
A Lustre expression is a term
Lift of [Term.is_true].
A Lustre type is a type
Lustre expression for the initial state
Lustre expression after initial state
Type of expression
Keep the type here instead of reading from expr_init or
expr_step, otherwise we need to get both types and merge
Bound for index variable, or fixed value for index variable
Upper bound for index variable
Fixed value for index variable
unbounded index variable
Total order on expressions
Equality on expressions
Hashing of expressions
Create a Lustre expression from a term and return a term, if
[init] is true considering [expr_init] only, otherwise [expr_step]
only.
Return term for initial state
Return term for step state
Apply function separately to init and step expression and
rebuild
Return the type of the expression
avoid cyclic type abbreviation
Equality on expressions
These offsets are different from the offsets in the transition system,
because here we want to know if the initial and the step
expressions are equal without bumping offsets.
Offset of state variable at current instant
Offset of state variable at previous instant
**********************************************************************
Pretty-printing
**********************************************************************
Pretty-print a type as a Lustre type
Pretty-print a symbol with a given type
Pretty-print a symbol as is
Pretty-print a variable
Pretty-printa variable with its type
Pretty-print a variable under [depth] pre operators
Variable is at an instant
Get state variable of variable
Function to pretty-print a variable with or without pre
Variable at current offset
Variable at previous offset
Fail on other offsets
Pretty-print state variable with or without pre
Variable is constant
Get state variable of variable
Fail on other types of variables
free variable
Pretty-print a term
Pretty-print a left-associative function application
Print (+ a b c) as (a + b + c)
Function application must have arguments, is a constant
otherwise
Pretty-print arguments of a right-associative function application
Function application must have arguments, is a constant
otherwise
Last or only argument
Print closing parentheses for all arguments
Print last argument and close all parentheses
Open parenthesis and print argument
Pretty-print a right-associative function application
Print (=> a b c) as (a => (b => c))
Pretty-print a chaining function application
Print (= a b c) as (a = b) and (b = c)
Last or only pair of arguments
Pretty-print a function application
Function application must have arguments, cannot have nullary
symbols here
Binary right-associative symbols
Chainable binary symbols
Binary non-associative symbols
if-then-else
Binary symbols
Divisibility
Unsupported functions symbols
Pretty-print a hashconsed term
Pretty-print a term as an expr.
(* Pretty-print a hashconsed term to the standard formatter
Same expression for initial state and following states
Print expression of initial state followed by expression for
following states
* Pretty-print a bound or fixed annotation
**********************************************************************
Predicates
**********************************************************************
Return true if expression is a previous state variable
Previous state variables have negative offset
Return true if there is an unguarded pre operator in the expression
Check if there is a pre operator in the init expression
Return true if expression is a current state variable
Term must be a free variable
Get free variable of term
Variable must be an instance of a state variable
Term must be a free variable
Get free variable of term
Variable must be an instance of a state variable
&&
StateVar.equal_state_vars
Return true if expression is a current state variable
Return true if expression is a constant state variable
Return true if expression is a previous state variable
Return true if the expression is constant
**********************************************************************
Conversion to terms
**********************************************************************
Instance of state variable at current instant
Instance of state variable at previous instant
(* Term of instance of state variable at previous instant
Term of instance of state variable at previous instant
Term of instance of state variable at current instant
Term of instance of state variable at previous instant
Term at current instant
Term at previous instant
Term at current instant
Term at previous instant
Return the state variable of a variable
Initial value and step value must be identical
Get free variable of term
Get instance of state variable
Fail if any of the above fails
Fail if initial value is different from step value
(* Return the free variable of a variable
Fail if any of the above fails
Return the free variable of a variable
Fail if any of the above fails
Return all state variables
Join sets of state variables
Return all state variables
Join sets of state variables
Return all state variables at the current instant in the initial
state expression
Return all state variables at the current instant in the initial
state expression
**********************************************************************
**********************************************************************
**********************************************************************
Constant constructors
**********************************************************************
Boolean constant true
Boolean constant false
Unsigned integer8 constant
Unsigned integer16 constant
Unsigned integer64 constant
Integer8 constant
Integer16 constant
Integer32 constant
Integer64 constant
Real constant
Current state variable of state variable
i-th index variable
create lustre expression for free variable
**********************************************************************
Type checking constructors
**********************************************************************
Type check for bool -> bool
Type check for bool -> bool -> bool
(* Type check for int -> int -> int
Type check for real -> real -> real
Best int subrange for some operator.
Type check for int -> int -> int, real -> real -> real
Type check for int -> int -> int, real -> real -> real,
abv -> abv -> abv
Type check for int -> int -> int, real -> real -> real,
bv -> bv -> bv
Type check for 'a -> 'a -> 'a
Extend integer ranges if one is not a subtype of the other
Fail if types are incompatible
Type check for bv -> bv -> bv or ubv -> ubv -> ubv
Type check for bv -> ubv -> bv or ubv -> ubv -> ubv
(* Type check for ubv -> ubv -> ubv
(* Type check for bv -> bv -> bv
Type check for 'a -> 'a -> bool
Extend integer ranges if one is not a subtype of the other
Fail if types are incompatible
Type check for int -> int -> bool, real -> real -> bool,
bv -> bv -> bool, ubv -> ubv -> bool
**********************************************************************
Evaluate unary negation
not true -> false
not false -> true
Type of unary negation
not: bool -> bool
**********************************************************************
Evaluate unary minus
-(c) -> (-c)
-(-x) -> x
**********************************************************************
Evaluate bitwise negation
Type of bitwise negation
**********************************************************************
Evaluate conversion to integer
Type of conversion to integer
int: real -> int
Conversion to integer
**********************************************************************
Evaluate conversion to unsigned integer8
Type of conversion to unsigned integer8
int: real -> uint8
Conversion to unsigned integer8
**********************************************************************
Evaluate conversion to unsigned integer16
Type of conversion to unsigned integer16
int: real -> uint16
Conversion to unsigned integer16
**********************************************************************
**********************************************************************
Evaluate conversion to unsigned integer64
Conversion to unsigned integer64
**********************************************************************
Evaluate conversion to integer8
Type of conversion to integer8
int: real -> int8
**********************************************************************
Evaluate conversion to integer16
Type of conversion to integer16
int: real -> int16
Conversion to integer16
**********************************************************************
**********************************************************************
Evaluate conversion to integer64
Conversion to integer64
**********************************************************************
Evaluate conversion to real
Type of conversion to real
real: int -> real
Conversion to integer
**********************************************************************
Evaluate Boolean conjunction
true and e2 -> e2
false and e2 -> false
e1 and true -> e1
e1 and false -> false
Type of Boolean conjunction
and: bool -> bool -> bool
n-ary Boolean conjunction
**********************************************************************
Evaluate Boolean disjunction
true or e2 -> true
false or e2 -> e2
e1 or true -> true
e1 or false -> e1
Type of Boolean disjunction
or: bool -> bool -> bool
Boolean disjunction
n-ary Boolean disjunction
**********************************************************************
Evaluate Boolean exclusive disjunction
true xor e2 -> not e2
false xor e2 -> e2
e1 xor true -> not e1
e1 xor false -> e1
**********************************************************************
Evaluate Boolean implication
true => e2 -> e2
false => e2 -> true
e1 => true -> true
e1 => false -> not e1
Type of Boolean implication
=>: bool -> bool -> bool
Boolean implication
**********************************************************************
**********************************************************************
**********************************************************************
Evaluate universal quantification
**********************************************************************
Evaluate existential quantification
Existential quantification
**********************************************************************
Evaluate integer modulus
**********************************************************************
Evaluate subtraction
Subtraction
**********************************************************************
Evaluate addition
Type of addition
If both summands are bounded, the sum is bounded by the sum of the
lower bound and the sum of the upper bounds.
+: int -> int -> int
real -> real -> real
Addition
**********************************************************************
Evaluate real division
Type of real division
/: real -> real -> real
When the operator is applied to integer and machine integer arguments,
its semantics is the same as integer division (div)
Real division
**********************************************************************
Evaluate multiplication
Type of multiplication
*: int -> int -> int
real -> real -> real
Multiplication
**********************************************************************
Evaluate integer division
Type of integer division
div: int -> int -> int
**********************************************************************
Evaluate bitvector conjunction
Type of bitvector conjunction
**********************************************************************
Evaluate bitvector disjunction
Type of bitvector disjunction
**********************************************************************
Evaluate bitvector left shift
Type of bitvector left shift
**********************************************************************
Evaluate bitvector (logical or arithmetic) right shift
Type of bitvector logical right shift
**********************************************************************
Evaluate equality
true = e2 -> e2
false = e2 -> not e2
e1 = true -> e1
e1 = false -> not e1
e = e -> true and e has no pre
Type of equality
=: 'a -> 'a -> bool
Equality
**********************************************************************
Evaluate disequality
Type of disequality
<>: 'a -> 'a -> bool
Disequality
**********************************************************************
Evaluate inequality
Bitvector comparisons are simplified in the simplify module
Type of inequality
<=: int -> int -> bool
real -> real -> bool
Disequality
**********************************************************************
Evaluate inequality
Bitvector comparisons are simplified in the simplify module
Type of inequality
<: int -> int -> bool
real -> real -> bool
Disequality
**********************************************************************
Evaluate inequality
Bitvector comparisons are simplified in the simplify module
Type of inequality
>=: int -> int -> bool
real -> real -> bool
Disequality
**********************************************************************
Evaluate inequality
Bitvector comparisons are simplified in the simplify module
Type of inequality
>=: int -> int -> bool
real -> real -> bool
Disequality
**********************************************************************
Evaluate if-then-else
Extend integer ranges if one is not a subtype of the other
If-then-else
**********************************************************************
Extend integer ranges if one is not a subtype of the other
Followed by expression
Types of expressions must be compatible
**********************************************************************
Pre expression
Expression is a constant not part of an unguarded pre expression
Expression is a variable at the current instant not part of an unguarded
pre expression
Expression is not a variable at the current instant or a constant:
abstract
AST Normalization makes this situation impossible
Stream is of the form: a -> b, abstract
AST Normalization makes this situation impossible
When simplifications fails, simply abstract with a new state variable,
i.e., create an internal new memory.
Fresh state variable for identifier
Abstraction at previous instant
Stream is the same in the initial state and step (e -> e)
Expression is a constant not part of an unguarded pre expression
Expression is a variable at the current instant not part of an unguarded
pre expression
Expression is not a variable at the current instant or a constant:
abstract
Stream is of the form: a -> b, abstract
**********************************************************************
Evaluate select from array
Nothing to simplify here
Type of A[k]
A[k]: array 'a 'b -> 'a -> 'b
Return type of array elements
Type of indexes do not match
Not an array type
Select from an array
Types of expressions must be compatible
Types of expressions must be compatible
**********************************************************************
Evaluate store from array
Nothing to simplify here
Return type of array
Type of indexes do not match
Not an array type
Store from an array
Type.pp_print_type (Type.index_type_of_array (type_of_lustre_expr expr1))
(pp_print_lustre_expr false) expr3
Types of expressions must be compatible
For an array select expression, get variable and list of indexes.
* XXX: We could implement var_of_array_select in terms of this, but this
* is stricter than var_of_array_select and will fail on different
* indexes in init vs step. Maybe that should be the case anyway?
**********************************************************************
Apply let binding for state variable at current instant to
expression
Split substitutions for initial state and step state
Apply substitutions separately
Apply let binding for state variable at previous instant to
expression
Split substitutions for initial state and step state
Apply substitutions separately
**********************************************************************
Return expression of a numeral | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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
-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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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
-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.
*)
open Lib
module I = LustreIdent
module SVS = StateVar.StateVarSet
module VS = Var.VarSet
exception Type_mismatch
exception NonConstantShiftOperand
type expr = Term.t
let is_true_expr e = e = Term.t_true
type lustre_type = Type.t
A typed expression
type t = {
expr_init: expr;
expr_step: expr;
expr_type: Type.t
}
type 'a bound_or_fixed =
let compare_expr = Term.compare
let compare
{ expr_init = init1; expr_step = step1 }
{ expr_init = init2; expr_step = step2 } =
comparision of initial value , step value
let c_init = compare_expr init1 init2 in
if c_init = 0 then compare_expr step1 step2 else c_init
let equal
{ expr_init = init1; expr_step = step1 }
{ expr_init = init2; expr_step = step2 } =
Term.equal init1 init2 && Term.equal step1 step2
let hash { expr_init; expr_step } =
Hashtbl.hash
(Term.hash expr_init, Term.hash expr_step)
Map on expression
We want to use the constructors of this module instead of the
functions of the term module to get type checking and
simplification . Therefore the function [ f ] gets values of type [ t ] ,
not of type [ expr ] .
A expression of type [ t ] has the [ - > ] only at the top with
the [ expr_init ] as the left operand and [ expr_step ] as the
right . We apply Term.map separately to [ expr_init ] and [ expr_step ] ,
which are of type [ expr = Term.t ] and construct a new Lustre
expression from the result .
When mapping [ expr_init ] , we know that we are on the left side of a
[ - > ] operator . If the result of [ f ] is [ l - > r ] we always take [ l ] ,
because [ ( l - > r ) - > t = ( l - > t ) ] . Same for [ expr_step ] , because
[ t - > ( l - > r ) = t - > r ] .
We want to use the constructors of this module instead of the
functions of the term module to get type checking and
simplification. Therefore the function [f] gets values of type [t],
not of type [expr].
A Lustre expression of type [t] has the [->] only at the top with
the [expr_init] as the left operand and [expr_step] as the
right. We apply Term.map separately to [expr_init] and [expr_step],
which are of type [expr = Term.t] and construct a new Lustre
expression from the result.
When mapping [expr_init], we know that we are on the left side of a
[->] operator. If the result of [f] is [l -> r] we always take [l],
because [(l -> r) -> t = (l -> t)]. Same for [expr_step], because
[t -> (l -> r) = t -> r].
*)
let map f { expr_init; expr_step } =
let f' init i term =
Construct Lustre expression from term , using the term for both
the initial state and the step state
the initial state and the step state *)
let expr =
{ expr_init = term;
expr_step = term;
expr_type = Term.type_of_term term }
in
Which of Init or step ?
if init then
(f i expr).expr_init
else
(f i expr).expr_step
in
let expr_init = Term.map (f' true) expr_init in
let expr_step = Term.map (f' false) expr_step in
let expr_type = Term.type_of_term expr_init in
{ expr_init; expr_step; expr_type }
let map_vars_expr = Term.map_vars
let map_vars f { expr_init = i; expr_step = s; expr_type = t } = {
expr_init = map_vars_expr f i;
expr_step = map_vars_expr f s;
expr_type = t
}
let rec map_top ' f term = match Term . T.node_of_t term with
| Term . T.FreeVar _ - > f term
| Term . T.Node ( s , _ ) when Symbol.equal_symbols s Symbol.s_select - > f term
| Term . term
| Term . T.Leaf _ - > term
| Term . T.Node ( s , l ) - > Term . T.mk_app s ( List.map ( map_array_var ' f ) l )
| Term . T.Let ( l , t ) - >
Term . T.mk_let_of_lambda ( map_array_var '' f l ) ( List.map ( map_array_var ' f ) t )
| Term . T.Exists l - >
Term . T.mk_exists_of_lambda ( map_array_var '' f l )
| Term . T.Forall l - >
Term . T.mk_forall_of_lambda ( map_array_var '' f l )
| Term . T.Annot ( t , a ) - > Term . T.mk_annot ( map_array_var ' f t ) a
and map_array_var '' f lambda = match Term . T.node_of_lambda lambda with
| Term . T.L ( l , t ) - > Term . T.mk_lambda_of_term l ( map_array_var ' f t )
let map_array_var f ( { expr_init ; expr_step } as expr ) =
{ expr with
expr_init = map_array_var ' f ' expr_init ;
expr_step = map_array_var ' f ' expr_step }
let rec map_top' f term = match Term.T.node_of_t term with
| Term.T.FreeVar _ -> f term
| Term.T.Node (s, _) when Symbol.equal_symbols s Symbol.s_select -> f term
| Term.T.BoundVar _ -> term
| Term.T.Leaf _ -> term
| Term.T.Node (s, l) -> Term.T.mk_app s (List.map (map_array_var' f) l)
| Term.T.Let (l, t) ->
Term.T.mk_let_of_lambda (map_array_var'' f l) (List.map (map_array_var' f) t)
| Term.T.Exists l ->
Term.T.mk_exists_of_lambda (map_array_var'' f l)
| Term.T.Forall l ->
Term.T.mk_forall_of_lambda (map_array_var'' f l)
| Term.T.Annot (t, a) -> Term.T.mk_annot (map_array_var' f t) a
and map_array_var'' f lambda = match Term.T.node_of_lambda lambda with
| Term.T.L (l, t) -> Term.T.mk_lambda_of_term l (map_array_var' f t)
let map_array_var f ({ expr_init; expr_step } as expr) =
{ expr with
expr_init = map_array_var' f' expr_init;
expr_step = map_array_var' f' expr_step }
*)
let type_of_lustre_expr { expr_type } = expr_type
let type_of_expr e = Term.type_of_term e
Hash table over expressions
module LustreExprHashtbl = Hashtbl.Make
(struct
type z = t
let equal = equal
let hash = hash
end)
let equal_expr = Term.equal
Offset of state variable at first instant
let base_offset = Numeral.zero
Offset of state variable at first instant
let pre_base_offset = Numeral.(pred base_offset)
let cur_offset = base_offset
let pre_offset = Numeral.(pred cur_offset)
let rec pp_print_lustre_type safe ppf t = match Type.node_of_type t with
| Type.Bool -> Format.pp_print_string ppf "bool"
| Type.Int -> Format.pp_print_string ppf "int"
| Type.IntRange (i, j, Type.Range) ->
Format.fprintf
ppf
"subrange [%a, %a] of int"
Numeral.pp_print_numeral i
Numeral.pp_print_numeral j
| Type.Real -> Format.pp_print_string ppf "real"
| Type.Abstr s -> Format.pp_print_string ppf s
| Type.IntRange (_, _, Type.Enum) ->
let cs = Type.constructors_of_enum t in
Format.fprintf ppf "enum {%a}"
(pp_print_list Format.pp_print_string ", ") cs
| Type.UBV i ->
begin match i with
| 8 -> Format.pp_print_string ppf "uint8"
| 16 -> Format.pp_print_string ppf "uint16"
| 32 -> Format.pp_print_string ppf "uint32"
| 64 -> Format.pp_print_string ppf "uint64"
| _ -> raise
(Invalid_argument "pp_print_lustre_type: UBV size not allowed")
end
| Type.BV i ->
begin match i with
| 8 -> Format.pp_print_string ppf "int8"
| 16 -> Format.pp_print_string ppf "int16"
| 32 -> Format.pp_print_string ppf "int32"
| 64 -> Format.pp_print_string ppf "int64"
| _ -> raise
(Invalid_argument "pp_print_lustre_type: BV size not allowed")
end
| Type.Array (s, _) ->
Format.fprintf ppf "array of %a" (pp_print_lustre_type safe) s
String representation of a symbol in
let string_of_symbol = function
| `TRUE -> "true"
| `FALSE -> "false"
| `NOT -> "not"
| `IMPLIES -> "=>"
| `AND -> "and"
| `OR -> "or"
| `EQ -> "="
| `NUMERAL n -> Numeral.string_of_numeral n
| `DECIMAL d -> Decimal.string_of_decimal_lustre d
| `XOR -> "xor"
| `UBV b ->
(match Bitvector.length_of_bitvector b with
| 8 -> "(uint8 " ^ (Numeral.string_of_numeral (Bitvector.ubv8_to_num b)) ^ ")"
| 16 -> "(uint16 " ^ (Numeral.string_of_numeral (Bitvector.ubv16_to_num b)) ^ ")"
| 32 -> "(uint32 " ^ (Numeral.string_of_numeral (Bitvector.ubv32_to_num b)) ^ ")"
| 64 -> "(uint64 " ^ (Numeral.string_of_numeral (Bitvector.ubv64_to_num b)) ^ ")"
| _ -> raise Type_mismatch)
| `BV b ->
(match Bitvector.length_of_bitvector b with
| 8 -> "(int8 " ^ (Numeral.string_of_numeral (Bitvector.bv8_to_num b)) ^ ")"
| 16 -> "(int16 " ^ (Numeral.string_of_numeral (Bitvector.bv16_to_num b)) ^ ")"
| 32 -> "(int32 " ^ (Numeral.string_of_numeral (Bitvector.bv32_to_num b)) ^ ")"
| 64 -> "(int64 " ^ (Numeral.string_of_numeral (Bitvector.bv64_to_num b)) ^ ")"
| _ -> raise Type_mismatch)
| `MINUS -> "-"
| `PLUS -> "+"
| `TIMES -> "*"
| `DIV -> "/"
| `INTDIV ->"div"
| `MOD -> "mod"
| `ABS -> "abs"
| `LEQ -> "<="
| `LT -> "<"
| `GEQ -> ">="
| `GT -> ">"
| `TO_REAL -> "real"
| `TO_INT -> "int"
| `TO_UINT8 -> "uint8"
| `TO_UINT16 -> "uint16"
| `TO_UINT32 -> "uint32"
| `TO_UINT64 -> "uint64"
| `TO_INT8 -> "int8"
| `TO_INT16 -> "int16"
| `TO_INT32 -> "int32"
| `TO_INT64 -> "int64"
| `BVAND -> "&&"
| `BVOR -> "||"
| `BVNOT -> "!"
| `BVNEG -> "-"
| `BVADD -> "+"
| `BVSUB -> "-"
| `BVMUL -> "*"
| `BVUDIV -> "div"
| `BVSDIV -> "div"
| `BVUREM -> "mod"
| `BVSREM -> "mod"
| `BVULT -> "<"
| `BVULE -> "<="
| `BVUGT -> ">"
| `BVUGE -> ">="
| `BVSLT -> "<"
| `BVSLE -> "<="
| `BVSGT -> ">"
| `BVSGE -> ">="
| `BVSHL -> "lshift"
| `BVLSHR -> "rshift"
| `BVASHR -> "arshift"
| `BVEXTRACT (i,j) -> "(_ extract " ^ (Numeral.string_of_numeral i) ^ " " ^ (Numeral.string_of_numeral j) ^ ")"
| `BVCONCAT -> "concat"
| `BVSIGNEXT i -> "(_ sign_extend " ^ (Numeral.string_of_numeral i) ^ ")"
| _ -> failwith "string_of_symbol"
let pp_print_symbol_as_type as_type ppf s =
match as_type, s with
| Some ty, `NUMERAL n when Type.is_enum ty ->
Type.get_constr_of_num n
|> Format.pp_print_string ppf
| _ ->
Format.pp_print_string ppf (string_of_symbol s)
let pp_print_symbol ppf s =
Format.pp_print_string ppf (string_of_symbol s)
let pp_print_lustre_var _ ppf state_var =
Format.fprintf ppf "%s" (StateVar.name_of_state_var state_var)
let pp_print_lustre_var_typed safe ppf state_var =
Format.fprintf ppf
"%t%a: %a"
(function ppf ->
if StateVar.is_const state_var then Format.fprintf ppf "const ")
(pp_print_lustre_var safe) state_var
(pp_print_lustre_type safe) (StateVar.type_of_state_var state_var)
let rec pp_print_var pvar ppf var =
if Var.is_state_var_instance var then
let state_var = Var.state_var_of_state_var_instance var in
let pp =
if Numeral.equal (Var.offset_of_state_var_instance var) cur_offset then
Format.fprintf ppf
"@[<hv 2>%a@]"
pvar
else if Numeral.equal (Var.offset_of_state_var_instance var) pre_offset then
Format.fprintf ppf
"@[<hv 2>(pre %a)@]"
pvar
else
function _ -> raise (Invalid_argument "pp_print_var")
in
pp state_var
else if Var.is_const_state_var var then
let state_var = Var.state_var_of_state_var_instance var in
Format.fprintf ppf
"@[<hv 2>%a@]"
pvar
state_var
else
Format.fprintf ppf "%s" (Var.string_of_var var)
and pp_print_term_node ?as_type safe pvar ppf t = match Term.T.destruct t with
| Term.T.Var var -> pp_print_var pvar ppf var
| Term.T.Const s ->
pp_print_symbol_as_type as_type ppf (Symbol.node_of_symbol s)
| Term.T.App (s, l) ->
pp_print_app ?as_type safe pvar ppf (Symbol.node_of_symbol s) l
| Term . T.Attr ( t , _ ) - >
pp_print_term_node ? as_type safe pvar ppf t
pp_print_term_node ?as_type safe pvar ppf t *)
| exception Invalid_argument ex -> (
match Term.T.node_of_t t with
| Term.T.Forall l -> (match Term.T.node_of_lambda l with
Term.T.L (_,t) -> (Format.fprintf ppf
"@[<hv 1>forall@ @[<hv 1>(...)@ %a@]@]"
(pp_print_term_node ?as_type safe pvar) t))
| Term.T.Exists l -> (match Term.T.node_of_lambda l with
Term.T.L (_,t) -> (Format.fprintf ppf
"@[<hv 1>exists@ @[<hv 1>(...)@ %a@]@]"
(pp_print_term_node ?as_type safe pvar) t))
| Term.T.BoundVar _ -> Term.T.pp_print_term ppf t
| _ -> raise (Invalid_argument ex)
)
Pretty - print the second and following arguments of a
left - associative function application
left-associative function application *)
and pp_print_app_left' safe pvar s ppf = function
| h :: tl ->
Format.fprintf ppf
" %a@ %a%t"
pp_print_symbol s
(pp_print_term_node safe pvar) h
(function ppf -> pp_print_app_left' safe pvar s ppf tl)
| [] -> ()
and pp_print_app_left safe pvar s ppf = function
| [] -> assert false
Print first argument
| h :: tl ->
Format.fprintf ppf
"@[<hv 2>(%a%t)@]"
(pp_print_term_node safe pvar) h
(function ppf -> pp_print_app_left' safe pvar s ppf tl)
and pp_print_app_right' safe pvar s arity ppf = function
| [] -> assert false
| [h] ->
let rec aux ppf = function
| 0 -> ()
| i ->
Format.fprintf ppf
"%t)@]"
(function ppf -> aux ppf (pred i))
in
Format.fprintf ppf
"%a%t"
(pp_print_term_node safe pvar) h
(function ppf -> aux ppf arity)
Second last or earlier argument
| h :: tl ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %t"
(pp_print_term_node safe pvar) h
pp_print_symbol s
(function ppf -> pp_print_app_right' safe pvar s arity ppf tl)
and pp_print_app_right safe pvar s ppf l =
pp_print_app_right' safe pvar s (List.length l - 1) ppf l
and pp_print_app_chain safe pvar s ppf = function
Chaining function application must have more than one argument
| []
| [_] -> assert false
| [l; r] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
Print function application of first pair , conjunction and continue
| l :: r :: tl ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a) and %a@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
(pp_print_app_chain safe pvar s) (r :: tl)
and pp_print_app ?as_type safe pvar ppf = function
| `TRUE
| `FALSE
| `NUMERAL _
| `DECIMAL _
| `UBV _
| `BV _
| `BV2NAT -> (function _ -> assert false)
Unary symbols
| `NOT
| `BVNOT
| `BVNEG
| `TO_REAL
| `TO_INT
| `UINT8_TO_INT
| `UINT16_TO_INT
| `UINT32_TO_INT
| `UINT64_TO_INT
| `INT8_TO_INT
| `INT16_TO_INT
| `INT32_TO_INT
| `INT64_TO_INT
| `TO_UINT8
| `TO_UINT16
| `TO_UINT32
| `TO_UINT64
| `TO_INT8
| `TO_INT16
| `TO_INT32
| `TO_INT64
| `BVEXTRACT _
| `BVSIGNEXT _
| `ABS as s ->
(function [a] ->
Format.fprintf ppf
"@[<hv 2>(%a@ %a)@]"
pp_print_symbol s
(pp_print_term_node safe pvar) a
| _ -> assert false)
Unary and left - associative binary symbols
| `MINUS as s ->
(function
| [] -> assert false
| [a] ->
Format.fprintf ppf
"%a%a"
pp_print_symbol s
(pp_print_term_node safe pvar) a
| _ as l -> pp_print_app_left safe pvar s ppf l)
Binary left - associative symbols with two or more arguments
| `AND
| `OR
| `XOR
| `BVAND
| `BVOR
| `BVADD
| `BVSUB
| `BVMUL
| `BVUDIV
| `BVSDIV
| `BVUREM
| `BVSREM
| `PLUS
| `TIMES
| `DIV
| `INTDIV as s ->
(function
| []
| [_] -> assert false
| _ as l -> pp_print_app_left safe pvar s ppf l)
| `IMPLIES as s -> pp_print_app_right safe pvar s ppf
| `EQ
| `BVULT
| `BVULE
| `BVUGT
| `BVUGE
| `BVSLT
| `BVSLE
| `BVSGT
| `BVSGE
| `LEQ
| `LT
| `GEQ
| `GT as s -> pp_print_app_chain safe pvar s ppf
| `BVSHL
| `BVLSHR
| `BVASHR as s ->
(function
| [a;b] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) a
pp_print_symbol s
(pp_print_term_node safe pvar) b
| _ -> assert false)
| `ITE ->
(function [p; l; r] ->
Format.fprintf ppf
"(if %a then %a else %a)"
(pp_print_term_node safe pvar) p
(pp_print_term_node ?as_type safe pvar) l
(pp_print_term_node ?as_type safe pvar) r
| _ -> assert false)
| `MOD as s ->
(function [l; r] ->
Format.fprintf ppf
"@[<hv 2>(%a %a@ %a)@]"
(pp_print_term_node safe pvar) l
pp_print_symbol s
(pp_print_term_node safe pvar) r
| _ -> assert false)
| `DIVISIBLE n ->
(function [a] ->
a divisble n becomes a mod n = 0
pp_print_app
safe
pvar
ppf
`EQ
[Term.T.mk_app
(Symbol.mk_symbol `MOD)
[a; Term.T.mk_const (Symbol.mk_symbol (`NUMERAL n))];
Term.T.mk_const (Symbol.mk_symbol (`NUMERAL Numeral.zero))]
| _ -> assert false)
| `SELECT _ ->
(function
| [a; i] ->
Format.fprintf ppf
"@[<hv 2>%a[%a]@]"
(pp_print_term_node safe pvar) a
(pp_print_term_node safe pvar) i
| _ -> assert false)
| `STORE ->
(function
| [a; i; v] ->
Format.fprintf ppf
"@[<hv 2>(%a with [%a] = %a)@]"
(pp_print_term_node safe pvar) a
(pp_print_term_node safe pvar) i
(pp_print_term_node safe pvar) v
| _ -> assert false)
| `UF sym as s when Symbol.is_select (Symbol.mk_symbol s) ->
pp_print_app ?as_type safe pvar ppf (`SELECT (UfSymbol.res_type_of_uf_symbol sym))
| `BVCONCAT
| `DISTINCT
| `IS_INT
| `UF _ -> (function _ -> assert false)
let pp_print_expr_pvar ?as_type safe pvar ppf expr =
pp_print_term_node ?as_type safe pvar ppf expr
let pp_print_expr ?as_type safe ppf expr =
pp_print_expr_pvar ?as_type safe (pp_print_lustre_var safe) ppf expr
let pp_print_term_as_expr = pp_print_expr
let pp_print_term_as_expr_pvar = pp_print_expr_pvar
let pp_print_term_as_expr_mvar ?as_type safe map ppf expr =
pp_print_term_as_expr_pvar
?as_type safe
(fun fmt sv ->
Format.fprintf fmt "%s"
(try
StateVar.StateVarMap.find sv map
with Not_found ->
StateVar.name_of_state_var sv)
)
ppf expr
let print_expr ?as_type safe =
pp_print_expr ?as_type safe Format.std_formatter
*)
Pretty - print a typed expression
let pp_print_lustre_expr safe ppf = function
| { expr_init; expr_step; expr_type }
when Term.equal expr_init expr_step ->
pp_print_expr ~as_type:expr_type safe ppf expr_step
| { expr_init; expr_step; expr_type } ->
Format.fprintf ppf
"@[<hv 1>(%a@ ->@ %a)@]"
(pp_print_expr ~as_type:expr_type safe) expr_init
(pp_print_expr ~as_type:expr_type safe) expr_step
let pp_print_bound_or_fixed ppf = function
| Bound x -> Format.fprintf ppf "@[<hv 1>(Bound %a)@]" (pp_print_expr true) x
| Fixed x -> Format.fprintf ppf "@[<hv 1>(Fixed %a)@]" (pp_print_expr true) x
| Unbound x -> Format.fprintf ppf "@[<hv 1>(Unbound %a)@]" (pp_print_expr true) x
let has_pre_var zero_offset { expr_step } =
match Term.var_offsets_of_term expr_step with
| Some n, _ when Numeral.(n <= zero_offset + pre_offset) -> true
| _ -> false
let pre_is_unguarded { expr_init } =
match Term.var_offsets_of_term expr_init with
| None, _ -> false
| Some c, _ -> Numeral.(c < base_offset)
let is_var_at_offset { expr_init; expr_step } (init_offset, step_offset) =
Term.is_free_var expr_init &&
let var_init = Term.free_var_of_term expr_init in
Var.is_state_var_instance var_init &&
Variable must be at instant zero
Numeral.(Var.offset_of_state_var_instance var_init = init_offset) &&
Term.is_free_var expr_step &&
let var_step = Term.free_var_of_term expr_step in
Var.is_state_var_instance var_step &&
Variable must be at instant zero
( )
( )
let is_var expr = is_var_at_offset expr (base_offset, cur_offset)
let is_const_var { expr_init; expr_step } =
Term.is_free_var expr_init && Term.is_free_var expr_step
&& Var.is_const_state_var (Term.free_var_of_term expr_init)
&& Var.is_const_state_var (Term.free_var_of_term expr_step)
let is_pre_var expr = is_var_at_offset expr (pre_base_offset, pre_offset)
let is_const_expr expr =
VS.for_all Var.is_const_state_var (Term.vars_of_term expr)
let is_const { expr_init; expr_step } =
is_const_expr expr_init && is_const_expr expr_step &&
Term.equal expr_init expr_step
Instance of state variable at instant zero
let pre_base_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
Numeral.(zero_offset |> pred)
Instance of state variable at instant zero
let base_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
zero_offset
let cur_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
zero_offset
let pre_var_of_state_var zero_offset state_var =
Var.mk_state_var_instance
state_var
Numeral.(zero_offset |> pred)
let pre_base_term_of_state_var zero_offset state_var =
pre_base_var_of_state_var zero_offset state_var
|> Term.mk_var
*)
let base_term_of_state_var zero_offset state_var =
base_var_of_state_var zero_offset state_var
|> Term.mk_var
let cur_term_of_state_var zero_offset state_var =
cur_var_of_state_var zero_offset state_var
|> Term.mk_var
let pre_term_of_state_var zero_offset state_var =
pre_var_of_state_var zero_offset state_var
|> Term.mk_var
Term at instant zero
let base_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - base_offset) expr
let cur_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - cur_offset) expr
let pre_term_of_expr zero_offset expr =
Term.bump_state Numeral.(zero_offset - cur_offset |> pred) expr
Term at instant zero
let base_term_of_t zero_offset { expr_init } =
base_term_of_expr zero_offset expr_init
let cur_term_of_t zero_offset { expr_step } =
cur_term_of_expr zero_offset expr_step
let pre_term_of_t zero_offset { expr_step } =
pre_term_of_expr zero_offset expr_step
let state_var_of_expr ({ expr_init } as expr) =
if is_var expr || is_pre_var expr then
try
let var = Term.free_var_of_term expr_init in
Var.state_var_of_state_var_instance var
with Invalid_argument _ -> raise (Invalid_argument "state_var_of_expr")
else
raise (Invalid_argument "state_var_of_expr")
let var_of_expr { expr_init } =
try
Term.free_var_of_term expr_init
with Invalid_argument _ -> raise (Invalid_argument "var_of_expr")
*)
let var_of_expr { expr_init } =
try
Term.free_var_of_term expr_init
with Invalid_argument _ -> raise (Invalid_argument "var_of_expr")
let state_vars_of_expr { expr_init; expr_step } =
State variables in initial state expression
let state_vars_init = Term.state_vars_of_term expr_init in
State variables in step state expression
let state_vars_step = Term.state_vars_of_term expr_step in
SVS.union state_vars_init state_vars_step
let vars_of_expr { expr_init; expr_step } =
State variables in initial state expression
let vars_init = Term.vars_of_term expr_init in
State variables in step state expression
let vars_step = Term.vars_of_term expr_step in
Var.VarSet.union vars_init vars_step
let base_state_vars_of_init_expr { expr_init } =
Term.state_vars_at_offset_of_term
base_offset
(base_term_of_expr base_offset expr_init)
let cur_state_vars_of_step_expr { expr_step } =
Term.state_vars_at_offset_of_term
cur_offset
(cur_term_of_expr cur_offset expr_step)
let indexes_of_state_vars_in_init sv { expr_init } =
Term.indexes_of_state_var sv expr_init
let indexes_of_state_vars_in_step sv { expr_step } =
Term.indexes_of_state_var sv expr_step
Split a list of expressions into a list of pairs of
expressions for the initial step and the transition steps ,
respectively
expressions for the initial step and the transition steps,
respectively *)
let split_expr_list list =
List.fold_left
(fun (accum_init, accum_step) { expr_init; expr_step } ->
((if expr_init == Term.t_true then
accum_init
else
expr_init :: accum_init),
(if expr_step == Term.t_true then
accum_step
else
expr_step :: accum_step)))
([], [])
list
Generic constructors
These constructors take as arguments functions [ eval ] and [ type_of ]
whose arity matches the arity of the constructors , where [ eval ]
applies the operator and simplifies the expression , and [ type_of ]
returns the type of the resulting expression or fails with
{ ! } .
whose arity matches the arity of the constructors, where [eval]
applies the operator and simplifies the expression, and [type_of]
returns the type of the resulting expression or fails with
{!Type_mismatch}. *)
Construct a unary expression
let mk_unary eval type_of expr =
let res_type = type_of expr.expr_type in
{ expr_init = eval expr.expr_init;
expr_step = eval expr.expr_step;
expr_type = res_type }
Construct a binary expression
let mk_binary eval type_of expr1 expr2 =
let res_type =
type_of expr1.expr_type expr2.expr_type
in
{ expr_init = eval expr1.expr_init expr2.expr_init;
expr_step = eval expr1.expr_step expr2.expr_step;
expr_type = res_type }
Construct a binary expression
let mk_ternary eval type_of expr1 expr2 expr3 =
let res_type =
type_of expr1.expr_type expr2.expr_type expr3.expr_type
in
{ expr_init = eval expr1.expr_init expr2.expr_init expr3.expr_init;
expr_step = eval expr1.expr_step expr2.expr_step expr3.expr_step;
expr_type = res_type }
let t_true =
let expr = Term.t_true in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bool }
let t_false =
let expr = Term.t_false in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bool }
let mk_constr c t =
let expr = Term.mk_constr c in
{ expr_init = expr;
expr_step = expr;
expr_type = t }
Integer constant
let mk_int d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.mk_int_range d d }
let mk_uint8 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 8 }
let mk_uint16 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 16 }
Unsigned integer32 constant
let mk_uint32 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 32 }
let mk_uint64 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_ubv 64 }
let mk_int8 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 8 }
let mk_int16 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 16 }
let mk_int32 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 32 }
let mk_int64 d =
let expr = Term.mk_num d in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_bv 64 }
let mk_real f =
let expr = Term.mk_dec f in
{ expr_init = expr;
expr_step = expr;
expr_type = Type.t_real }
let mk_var state_var =
{ expr_init = base_term_of_state_var base_offset state_var;
expr_step = cur_term_of_state_var cur_offset state_var;
expr_type = StateVar.type_of_state_var state_var }
let mk_free_var v =
let t = Term.mk_var v in
{ expr_init = t;
expr_step = t;
expr_type = Var.type_of_var v }
let mk_index_var i =
let v =
Var.mk_free_var
(String.concat "."
(((I.push_index I.index_ident i) |> I.string_of_ident true)
:: I.reserved_scope)
|> HString.mk_hstring)
Type.t_int
|> Term.mk_var
in
{ expr_init = v;
expr_step = v;
expr_type = Type.t_int }
let int_of_index_var { expr_init = t } =
if not (Term.is_free_var t) then raise (Invalid_argument "int_of_index_var");
let v = Term.free_var_of_term t in
let s = Var.hstring_of_free_var v |> HString.string_of_hstring in
try Scanf.sscanf s ("__index_%d%_s") (fun i -> i)
with Scanf.Scan_failure _ -> raise (Invalid_argument "int_of_index_var")
let has_q_index_expr e =
let vs = Term.vars_of_term e in
Var.VarSet.exists (fun v ->
Var.is_free_var v &&
let s = Var.hstring_of_free_var v |> HString.string_of_hstring in
try Scanf.sscanf s ("__index_%_d%_s") true
with Scanf.Scan_failure _ -> false
) vs
let has_indexes { expr_init; expr_step } =
has_q_index_expr expr_init || has_q_index_expr expr_step
Generic type checking functions that fail with [ Type_mismatch ] or
return a resulting type if the expressions match the required types .
return a resulting type if the expressions match the required types. *)
let type_of_bool_bool = function
| t when Type.is_bool t -> Type.t_bool
| _ -> raise Type_mismatch
let type_of_bool_bool_bool = function
| t when Type.is_bool t ->
(function
| t when Type.is_bool t -> Type.t_bool
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
let type_of_int_int_int = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
let type_of_real_real_real = function
| t when Type.is_real t ->
(function
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
*)
let best_int_range is_div op t t' =
match Type.bounds_of_int_range t' with
| lo', hi' when (
is_div &&
Numeral.(equal lo' zero) &&
Numeral.(equal hi' zero)
) -> raise Division_by_zero
| lo', _ when (
is_div && Numeral.(equal lo' zero)
) -> Type.t_int
| _, hi' when (
is_div && Numeral.(equal hi' zero)
)-> Type.t_int
| lo', hi' ->
let lo, hi = Type.bounds_of_int_range t in
let b_0 = op lo lo' in
let bounds =
[ op hi lo' ;
op lo hi' ;
op hi hi' ]
in
Type.mk_int_range
(List.fold_left Numeral.min b_0 bounds)
(List.fold_left Numeral.max b_0 bounds)
let type_of_num_num_num ? ( is_div = false ) op t t ' =
try best_int_range is_div op t t ' with
| Invalid_argument _ - > (
match t with
| t when Type.is_int t || Type.is_int_range t - > (
match t ' with
| t when Type.is_int t || Type.is_int_range t - > Type.t_int
| _ - > raise Type_mismatch
)
| t when Type.is_real t - > (
match t ' with
| t when Type.is_real t - > Type.t_real
| _ - > raise Type_mismatch
)
| _ - > raise )
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch
)
| _ -> raise Type_mismatch
)
*)
let type_of_numOrBV_numOrBV_numOrBV ?(is_div = false) op t t' =
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_uint8 t -> (
match t' with
| t when Type.is_uint8 t -> Type.t_ubv 8
| _ -> raise Type_mismatch)
| t when Type.is_uint16 t -> (
match t' with
| t when Type.is_uint16 t -> Type.t_ubv 16
| _ -> raise Type_mismatch)
| t when Type.is_uint32 t -> (
match t' with
| t when Type.is_uint32 t -> Type.t_ubv 32
| _ -> raise Type_mismatch)
| t when Type.is_uint64 t -> (
match t' with
| t when Type.is_uint64 t -> Type.t_ubv 64
| _ -> raise Type_mismatch)
| t when Type.is_int8 t -> (
match t' with
| t when Type.is_int8 t -> Type.t_bv 8
| _ -> raise Type_mismatch)
| t when Type.is_int16 t -> (
match t' with
| t when Type.is_int16 t -> Type.t_bv 16
| _ -> raise Type_mismatch)
| t when Type.is_int32 t -> (
match t' with
| t when Type.is_int32 t -> Type.t_bv 32
| _ -> raise Type_mismatch)
| t when Type.is_int64 t -> (
match t' with
| t when Type.is_int64 t -> Type.t_bv 64
| _ -> raise Type_mismatch)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
let type_of_numOrSBV_numOrSBV_numOrSBV ?(is_div = false) op t t' =
try best_int_range is_div op t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_int8 t -> (
match t' with
| t when Type.is_int8 t -> Type.t_bv 8
| _ -> raise Type_mismatch)
| t when Type.is_int16 t -> (
match t' with
| t when Type.is_int16 t -> Type.t_bv 16
| _ -> raise Type_mismatch)
| t when Type.is_int32 t -> (
match t' with
| t when Type.is_int32 t -> Type.t_bv 32
| _ -> raise Type_mismatch)
| t when Type.is_int64 t -> (
match t' with
| t when Type.is_int64 t -> Type.t_bv 64
| _ -> raise Type_mismatch)
| t when Type.is_real t -> (
match t' with
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
let type_of_a_a_a type1 type2 =
If first type is subtype of second , choose second type
if Type.check_type type1 type2 then type2
If second type is subtype of first , choose first type
else if Type.check_type type2 type1 then type1
else if Type.is_int_range type1 && Type.is_int_range type2 then Type.t_int
else raise Type_mismatch
let type_of_abv_abv_abv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| t, t' when Type.is_int8 t && Type.is_int8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_int16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_int32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_int64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
let type_of_abv_ubv_abv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| t, t' when Type.is_int8 t && Type.is_uint8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_uint16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_uint32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_uint64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
let type_of_ubv_ubv_ubv t t' =
match t, t' with
| t, t' when Type.is_uint8 t && Type.is_uint8 t' -> Type.t_ubv 8
| t, t' when Type.is_uint16 t && Type.is_uint16 t' -> Type.t_ubv 16
| t, t' when Type.is_uint32 t && Type.is_uint32 t' -> Type.t_ubv 32
| t, t' when Type.is_uint64 t && Type.is_uint64 t' -> Type.t_ubv 64
| _, _ -> raise Type_mismatch
*)
let type_of_bv_bv_bv t t' =
match t, t' with
| t, t' when Type.is_int8 t && Type.is_int8 t' -> Type.t_bv 8
| t, t' when Type.is_int16 t && Type.is_int16 t' -> Type.t_bv 16
| t, t' when Type.is_int32 t && Type.is_int32 t' -> Type.t_bv 32
| t, t' when Type.is_int64 t && Type.is_int64 t' -> Type.t_bv 64
| _, _ -> raise Type_mismatch
*)
let type_of_a_a_bool type1 type2 =
if
One type must be subtype of the other
Type.check_type type1 type2
|| Type.check_type type2 type1
|| (Type.is_int_range type1 && Type.is_int_range type2)
then
Resulting type is Boolean
Type.t_bool
else
raise Type_mismatch
let type_of_num_num_bool = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t || Type.is_int_range t -> Type.t_bool
| _ -> raise Type_mismatch)
| t when Type.is_real t ->
(function
| t when Type.is_real t -> Type.t_bool
| _ -> raise Type_mismatch)
| t when Type.is_ubitvector t ->
(function
| t' when Type.is_ubitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
(match s1, s2 with
| 8,8 -> Type.t_bool
| 16,16 -> Type.t_bool
| 32,32 -> Type.t_bool
| 64,64 -> Type.t_bool
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t ->
(function
| t' when Type.is_bitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
(match s1, s2 with
| 8,8 -> Type.t_bool
| 16,16 -> Type.t_bool
| 32,32 -> Type.t_bool
| 64,64 -> Type.t_bool
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
let eval_not = function
| t when t == Term.t_true -> Term.t_false
| t when t == Term.t_false -> Term.t_true
| expr -> Term.mk_not expr
let type_of_not = type_of_bool_bool
Unary negation of expression
let mk_not expr = mk_unary eval_not type_of_not expr
let eval_uminus expr = match Term.destruct expr with
| Term.T.Const s when Symbol.is_numeral s ->
Term.mk_num Numeral.(- Symbol.numeral_of_symbol s)
| Term.T.Const s when Symbol.is_decimal s ->
Term.mk_dec Decimal.(- Symbol.decimal_of_symbol s)
| Term.T.App (s, [e]) when s == Symbol.s_minus -> e
| _ -> if (Type.is_bitvector (Term.type_of_term expr) ||
Type.is_ubitvector (Term.type_of_term expr)) then
Term.mk_bvneg expr
else
Term.mk_minus [expr]
| exception Invalid_argument _ -> Term.mk_minus [expr]
Type of unary minus
- : int - > int
- : int_range(l , u ) - > int_range(-u , -l )
- : real - > real
-: int -> int
-: int_range(l, u) -> int_range(-u, -l)
-: real -> real
*)
let type_of_uminus = function
| t when Type.is_int t -> Type.t_int
| t when Type.is_real t -> Type.t_real
| t when Type.is_int_range t ->
let (lbound, ubound) = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(- ubound) Numeral.(- lbound)
| t when Type.is_int8 t -> Type.t_bv 8
| t when Type.is_int16 t -> Type.t_bv 16
| t when Type.is_int32 t -> Type.t_bv 32
| t when Type.is_int64 t -> Type.t_bv 64
| t when Type.is_uint8 t -> Type.t_ubv 8
| t when Type.is_uint16 t -> Type.t_ubv 16
| t when Type.is_uint32 t -> Type.t_ubv 32
| t when Type.is_uint64 t -> Type.t_ubv 64
| _ -> raise Type_mismatch
Unary negation of expression
let mk_uminus expr = mk_unary eval_uminus type_of_uminus expr
let eval_bvnot expr = Term.mk_bvnot expr
let type_of_bvnot = function
| t when Type.is_ubitvector t ->
let s = Type.bitvectorsize t in
(match s with
| 8 -> Type.t_ubv 8
| 16 -> Type.t_ubv 16
| 32 -> Type.t_ubv 32
| 64 -> Type.t_ubv 64
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t ->
let s = Type.bitvectorsize t in
(match s with
| 8 -> Type.t_bv 8
| 16 -> Type.t_bv 16
| 32 -> Type.t_bv 32
| 64 -> Type.t_bv 64
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
Unary negation of expression
let mk_bvnot expr = mk_unary eval_bvnot type_of_bvnot expr
let eval_to_int expr =
let tt = Term.type_of_term expr in
if Type.is_int tt || Type.is_int_range tt then
expr
else
match Term.destruct expr with
| Term.T.Const s when Symbol.is_decimal s ->
Term.mk_num
(Numeral.of_big_int
(Decimal.to_big_int
(Symbol.decimal_of_symbol s)))
| Term.T.Const s when Symbol.is_ubv8 s ->
Term.mk_num
(Bitvector.ubv8_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv16 s ->
Term.mk_num
(Bitvector.ubv16_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv32 s ->
Term.mk_num
(Bitvector.ubv32_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_ubv64 s ->
Term.mk_num
(Bitvector.ubv64_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv8 s ->
Term.mk_num
(Bitvector.bv8_to_num
(Symbol.bitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv16 s ->
Term.mk_num
(Bitvector.bv16_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv32 s ->
Term.mk_num
(Bitvector.bv32_to_num
(Symbol.ubitvector_of_symbol s))
| Term.T.Const s when Symbol.is_bv64 s ->
Term.mk_num
(Bitvector.bv64_to_num
(Symbol.ubitvector_of_symbol s))
| x when Type.is_uint8 (Term.type_of_term (Term.construct x)) -> Term.mk_uint8_to_int expr
| x when Type.is_uint16 (Term.type_of_term (Term.construct x)) -> Term.mk_uint16_to_int expr
| x when Type.is_uint32 (Term.type_of_term (Term.construct x)) -> Term.mk_uint32_to_int expr
| x when Type.is_uint64 (Term.type_of_term (Term.construct x)) -> Term.mk_uint64_to_int expr
| x when Type.is_int8 (Term.type_of_term (Term.construct x)) -> Term.mk_int8_to_int expr
| x when Type.is_int16 (Term.type_of_term (Term.construct x)) -> Term.mk_int16_to_int expr
| x when Type.is_int32 (Term.type_of_term (Term.construct x)) -> Term.mk_int32_to_int expr
| x when Type.is_int64 (Term.type_of_term (Term.construct x)) -> Term.mk_int64_to_int expr
| _ -> Term.mk_to_int expr
| exception Invalid_argument _ ->
if Type.is_uint8 (Term.type_of_term expr) then
Term.mk_uint8_to_int expr
else if Type.is_uint16 (Term.type_of_term expr) then
Term.mk_uint16_to_int expr
else if Type.is_uint32 (Term.type_of_term expr) then
Term.mk_uint32_to_int expr
else if Type.is_uint64 (Term.type_of_term expr) then
Term.mk_uint64_to_int expr
else if Type.is_int8 (Term.type_of_term expr) then
Term.mk_int8_to_int expr
else if Type.is_int16 (Term.type_of_term expr) then
Term.mk_int16_to_int expr
else if Type.is_int32 (Term.type_of_term expr) then
Term.mk_int32_to_int expr
else if Type.is_int64 (Term.type_of_term expr) then
Term.mk_int64_to_int expr
else
Term.mk_to_int expr
let type_of_to_int = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_int
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int32 t || Type.is_int64 t -> Type.t_int
| _ -> raise Type_mismatch
let mk_to_int expr = mk_unary eval_to_int type_of_to_int expr
let eval_to_uint8 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv8 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv8 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint8 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint8 tt) then
expr
else
Term.mk_bvextract (Numeral.of_int 7) (Numeral.of_int 0) expr
else
raise Type_mismatch
let type_of_to_uint8 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint8 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 8
| t when Type.is_uint16 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_ubv 8
| _ -> raise Type_mismatch
let mk_to_uint8 expr = mk_unary eval_to_uint8 type_of_to_uint8 expr
let eval_to_uint16 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv16 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv16 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint16 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint16 tt) then
expr
else if (Type.is_uint8 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 8)) expr
else
Term.mk_bvextract (Numeral.of_int 15) (Numeral.of_int 0) expr
else
raise Type_mismatch
let type_of_to_uint16 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint16 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 16
| t when Type.is_uint8 t || Type.is_uint32 t || Type.is_uint64 t -> Type.t_ubv 16
| _ -> raise Type_mismatch
let mk_to_uint16 expr = mk_unary eval_to_uint16 type_of_to_uint16 expr
Evaluate conversion to unsigned integer32
let eval_to_uint32 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv32 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv32 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint32 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint32 tt) then
expr
else if (Type.is_uint8 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 24)) expr
else if (Type.is_uint16 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 16)) expr
else
Term.mk_bvextract (Numeral.of_int 31) (Numeral.of_int 0) expr
let n = Term.mk_bv2nat expr in
Term.mk_to_uint32 n
Term.mk_to_uint32 n*)
else
raise Type_mismatch
Type of conversion to unsigned integer32
int : real - > uint32
int: real -> uint32
*)
let type_of_to_uint32 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint32 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 32
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint64 t -> Type.t_ubv 32
| _ -> raise Type_mismatch
Conversion to unsigned integer32
let mk_to_uint32 expr = mk_unary eval_to_uint32 type_of_to_uint32 expr
let eval_to_uint64 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_ubv (Bitvector.num_to_ubv64 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_ubv
(Bitvector.num_to_ubv64 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_uint64 expr
else if (Type.is_ubitvector tt) then
if (Type.is_uint64 tt) then
expr
else if (Type.is_uint32 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 32)) expr
else if (Type.is_uint16 tt) then
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 48)) expr
else
Term.mk_bvconcat (Term.mk_ubv (Bitvector.zero 56)) expr
else
raise Type_mismatch
Type of conversion to unsigned integer64
int : real - > int64
int: real -> int64
*)
let type_of_to_uint64 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_uint64 t || Type.is_int t || Type.is_int_range t -> Type.t_ubv 64
| t when Type.is_uint8 t || Type.is_uint16 t || Type.is_uint32 t -> Type.t_ubv 64
| _ -> raise Type_mismatch
let mk_to_uint64 expr = mk_unary eval_to_uint64 type_of_to_uint64 expr
let eval_to_int8 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv8 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv8 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int8 expr
else if (Type.is_bitvector tt) then
if (Type.is_int8 tt) then
expr
else
Term.mk_bvextract (Numeral.of_int 7) (Numeral.of_int 0) expr
else
raise Type_mismatch
let type_of_to_int8 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int8 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 8
| t when Type.is_int16 t || Type.is_int32 t || Type.is_int64 t -> Type.t_bv 8
| _ -> raise Type_mismatch
Conversion to integer8
let mk_to_int8 expr = mk_unary eval_to_int8 type_of_to_int8 expr
let eval_to_int16 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv16 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv16 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int16 expr
else if (Type.is_bitvector tt) then
if (Type.is_int16 tt) then
expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 8) expr
else
Term.mk_bvextract (Numeral.of_int 15) (Numeral.of_int 0) expr
else
raise Type_mismatch
let type_of_to_int16 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int16 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 16
| t when Type.is_int8 t || Type.is_int32 t || Type.is_int64 t -> Type.t_bv 16
| _ -> raise Type_mismatch
let mk_to_int16 expr = mk_unary eval_to_int16 type_of_to_int16 expr
Evaluate conversion to integer32
let eval_to_int32 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv32 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv32 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int32 expr
else if (Type.is_bitvector tt) then
if (Type.is_int32 tt) then
expr
else if (Type.is_int64 tt) then
Term.mk_bvextract (Numeral.of_int 31) (Numeral.of_int 0) expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 24) expr
else
Term.mk_bvsignext (Numeral.of_int 16) expr
else
raise Type_mismatch
Type of conversion to integer32
int : real - > int32
int: real -> int32
*)
let type_of_to_int32 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int32 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 32
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int64 t -> Type.t_bv 32
| _ -> raise Type_mismatch
Conversion to integer32
let mk_to_int32 expr = mk_unary eval_to_int32 type_of_to_int32 expr
let eval_to_int64 expr =
match Term.destruct expr with
| Term.T.Const c when Symbol.is_numeral c ->
Term.mk_bv (Bitvector.num_to_bv64 (Symbol.numeral_of_symbol c))
| Term.T.App (_, [ sub_expr ])
when Term.is_negative_numeral expr ->
Term.mk_bv
(Bitvector.num_to_bv64 (Numeral.neg (Term.numeral_of_term sub_expr)))
| _ -> let tt = Term.type_of_term expr in
if (Type.is_int tt) then
Term.mk_to_int64 expr
else if (Type.is_bitvector tt) then
if (Type.is_int64 tt) then
expr
else if (Type.is_int8 tt) then
Term.mk_bvsignext (Numeral.of_int 56) expr
else if (Type.is_int16 tt) then
Term.mk_bvsignext (Numeral.of_int 48) expr
else
Term.mk_bvsignext (Numeral.of_int 32) expr
else
raise Type_mismatch
Type of conversion to integer64
int : real - > int64
int: real -> int64
*)
let type_of_to_int64 = function
| t when Type.is_real t -> Type.t_int
| t when Type.is_int64 t || Type.is_int t || Type.is_int_range t -> Type.t_bv 64
| t when Type.is_int8 t || Type.is_int16 t || Type.is_int32 t -> Type.t_bv 64
| _ -> raise Type_mismatch
let mk_to_int64 expr = mk_unary eval_to_int64 type_of_to_int64 expr
let eval_to_real expr =
let tt = Term.type_of_term expr in
if Type.is_real tt then
expr
else
match Term.destruct expr with
| Term.T.Const s when Symbol.is_numeral s ->
Term.mk_dec
(Decimal.of_big_int
(Numeral.to_big_int
(Symbol.numeral_of_symbol s)))
| _ -> Term.mk_to_real expr
| exception Invalid_argument _ -> Term.mk_to_real expr
let type_of_to_real = function
| t when Type.is_int t || Type.is_int_range t -> Type.t_real
| t when Type.is_real t -> Type.t_real
| _ -> raise Type_mismatch
let mk_to_real expr = mk_unary eval_to_real type_of_to_real expr
let eval_and = function
| t when t == Term.t_true -> (function expr2 -> expr2)
| t when t == Term.t_false -> (function _ -> Term.t_false)
| expr1 ->
(function
| t when t == Term.t_true -> expr1
| t when t == Term.t_false -> Term.t_false
| expr2 -> Term.mk_and [expr1; expr2])
let type_of_and = type_of_bool_bool_bool
Boolean conjunction
let mk_and expr1 expr2 = mk_binary eval_and type_of_and expr1 expr2
let mk_and_n = function
| [] -> t_true
| h :: [] -> h
| h :: tl -> List.fold_left mk_and h tl
let eval_or = function
| t when t == Term.t_true -> (function _ -> Term.t_true)
| t when t == Term.t_false -> (function expr2 -> expr2)
| expr1 ->
(function
| t when t == Term.t_true -> Term.t_true
| t when t == Term.t_false -> expr1
| expr2 -> Term.mk_or [expr1; expr2])
let type_of_or = type_of_bool_bool_bool
let mk_or expr1 expr2 = mk_binary eval_or type_of_or expr1 expr2
let mk_or_n = function
| [] -> t_true
| h :: [] -> h
| h :: tl -> List.fold_left mk_or h tl
let eval_xor = function
| t when t == Term.t_true -> (function expr2 -> eval_not expr2)
| t when t == Term.t_false -> (function expr2 -> expr2)
| expr1 ->
(function
| t when t == Term.t_true -> eval_not expr1
| t when t == Term.t_false -> expr1
| expr2 -> Term.mk_xor [expr1; expr2])
Type of Boolean exclusive disjunction
xor : bool - > bool - > bool
xor: bool -> bool -> bool *)
let type_of_xor = type_of_bool_bool_bool
Boolean exclusive disjunction
let mk_xor expr1 expr2 = mk_binary eval_xor type_of_xor expr1 expr2
let eval_impl = function
| t when t == Term.t_true -> (function expr2 -> expr2)
| t when t == Term.t_false -> (function _ -> Term.t_true)
| expr1 ->
(function
| t when t == Term.t_true -> Term.t_true
| t when t == Term.t_false -> eval_not expr1
| expr2 -> Term.mk_implies [expr1; expr2])
let type_of_impl = type_of_bool_bool_bool
let mk_impl expr1 expr2 = mk_binary eval_impl type_of_impl expr1 expr2
let mk_let bindings expr =
{
expr_init = Term.mk_let bindings expr.expr_init;
expr_step = Term.mk_let bindings expr.expr_step;
expr_type = expr.expr_type;
}
let apply_subst sigma expr =
{
expr_init = Term.apply_subst sigma expr.expr_init;
expr_step = Term.apply_subst sigma expr.expr_step;
expr_type = expr.expr_type;
}
let eval_forall vars t = match vars, t with
| [], _ -> Term.t_true
| _, t when t == Term.t_true -> Term.t_true
| _, t when t == Term.t_false -> Term.t_false
| _ -> Term.mk_forall vars t
let type_of_forall = type_of_bool_bool
Universal quantification
let mk_forall vars expr =
mk_unary (eval_forall vars) type_of_forall expr
let eval_exists vars t = match vars, t with
| [], _ -> Term.t_false
| _, t when t == Term.t_true -> Term.t_true
| _, t when t == Term.t_false -> Term.t_false
| _ -> Term.mk_exists vars t
let type_of_exists = type_of_bool_bool
let mk_exists vars expr = mk_unary (eval_exists vars) type_of_exists expr
let eval_mod expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 mod
Symbol.numeral_of_symbol c2)
| _ -> (if Type.is_ubitvector (Term.type_of_term expr1) then
Term.mk_bvurem [expr1; expr2]
else if Type.is_bitvector (Term.type_of_term expr1) then
Term.mk_bvsrem [expr1; expr2]
else
Term.mk_mod expr1 expr2)
| exception Invalid_argument _ -> Term.mk_mod expr1 expr2
Type of integer modulus
If j is bounded by [ l , u ] , then the result of i mod j is bounded by
[ 0 , ( max(|l| , |u| ) - 1 ) ] .
mod : int - > int - > int
If j is bounded by [l, u], then the result of i mod j is bounded by
[0, (max(|l|, |u|) - 1)].
mod: int -> int -> int *)
let type_of_mod = function
| t when Type.is_int t || Type.is_int_range t ->
(function
| t when Type.is_int t -> Type.t_int
| t when Type.is_int_range t ->
let l, u = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.zero Numeral.(pred (max (abs l) (abs u)))
| _ -> raise Type_mismatch)
| t1 when Type.is_ubitvector t1 ->
(function
| t2 when Type.is_ubitvector t2 ->
let s1 = Type.bitvectorsize t1 in
let s2 = Type.bitvectorsize t2 in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_ubv 8
| 16, 16 -> Type.t_ubv 16
| 32, 32 -> Type.t_ubv 32
| 64, 64 -> Type.t_ubv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t1 when Type.is_bitvector t1 ->
(function
| t2 when Type.is_bitvector t2 ->
let s1 = Type.bitvectorsize t1 in
let s2 = Type.bitvectorsize t2 in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_bv 8
| 16, 16 -> Type.t_bv 16
| 32, 32 -> Type.t_bv 32
| 64, 64 -> Type.t_bv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
Integer modulus
let mk_mod expr1 expr2 = mk_binary eval_mod type_of_mod expr1 expr2
let eval_minus expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 -
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 -
Symbol.decimal_of_symbol c2)
| _ -> (if ((Type.is_bitvector (Term.type_of_term expr1))
|| (Type.is_ubitvector (Term.type_of_term expr1))) then
Term.mk_bvsub [expr1; expr2]
else
Term.mk_minus [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_minus [expr1; expr2]
Type of subtraction
If both arguments are bounded , the difference is bounded by the
difference of the lower bound of the first argument and the upper
bound of the second argument and the difference of the upper bound
of the first argument and the lower bound of the second argument .
- : int - > int - > int
real - > real - > real
If both arguments are bounded, the difference is bounded by the
difference of the lower bound of the first argument and the upper
bound of the second argument and the difference of the upper bound
of the first argument and the lower bound of the second argument.
-: int -> int -> int
real -> real -> real *)
let type_of_minus = function
| t when Type.is_int_range t ->
(function
| s when Type.is_int_range s ->
let l1, u1 = Type.bounds_of_int_range t in
let l2, u2 = Type.bounds_of_int_range s in
Type.mk_int_range Numeral.(l1 - u2) Numeral.(u1 - l2)
| s -> type_of_numOrSBV_numOrSBV_numOrSBV Numeral.sub t s)
| t -> type_of_numOrBV_numOrBV_numOrBV Numeral.sub t
let mk_minus expr1 expr2 = mk_binary eval_minus type_of_minus expr1 expr2
let eval_plus expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 +
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 +
Symbol.decimal_of_symbol c2)
| _ -> (if (((Type.is_bitvector (Term.type_of_term expr1))
&& (Type.is_bitvector (Term.type_of_term expr2)))
||
((Type.is_ubitvector (Term.type_of_term expr1))
&& (Type.is_ubitvector (Term.type_of_term expr1)))) then
Term.mk_bvadd [expr1; expr2]
else
Term.mk_plus [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_plus [expr1; expr2]
let type_of_plus = function
| t when Type.is_int_range t ->
(function
| s when Type.is_int_range s ->
let l1, u1 = Type.bounds_of_int_range t in
let l2, u2 = Type.bounds_of_int_range s in
Type.mk_int_range Numeral.(l1 + l2) Numeral.(u1 + u2)
| s -> type_of_numOrBV_numOrBV_numOrBV Numeral.add t s)
| t -> type_of_numOrBV_numOrBV_numOrBV Numeral.add t
let mk_plus expr1 expr2 = mk_binary eval_plus type_of_plus expr1 expr2
let eval_div expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 ->
if Symbol.is_decimal c1 && Symbol.is_decimal c2 then
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 /
Symbol.decimal_of_symbol c2)
else (
assert (Symbol.is_numeral c1 && Symbol.is_numeral c2);
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 /
Symbol.numeral_of_symbol c2)
)
| _ ->
let tt = Term.type_of_term expr1 in
if Type.is_real tt then (
Term.mk_div [expr1; expr2]
)
else if Type.is_ubitvector (Term.type_of_term expr1) then (
Term.mk_bvudiv [expr1; expr2]
)
else if Type.is_bitvector (Term.type_of_term expr1) then (
Term.mk_bvsdiv [expr1; expr2]
)
else (
Term.mk_intdiv [expr1; expr2]
)
| exception Invalid_argument _ -> Term.mk_div [expr1; expr2]
let type_of_div = type_of_numOrBV_numOrBV_numOrBV ~is_div:true Numeral.div
let mk_div expr1 expr2 = mk_binary eval_div type_of_div expr1 expr2
let eval_times expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 *
Symbol.numeral_of_symbol c2)
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 && Symbol.is_decimal c2 ->
Term.mk_dec
Decimal.(Symbol.decimal_of_symbol c1 *
Symbol.decimal_of_symbol c2)
| _ -> (if (Type.is_bitvector (Term.type_of_term expr1) ||
Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvmul [expr1; expr2]
else
Term.mk_times [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_times [expr1; expr2]
let type_of_times = type_of_numOrBV_numOrBV_numOrBV Numeral.mult
let mk_times expr1 expr2 = mk_binary eval_times type_of_times expr1 expr2
let eval_intdiv expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 && Symbol.is_numeral c2 ->
Term.mk_num
Numeral.(Symbol.numeral_of_symbol c1 /
Symbol.numeral_of_symbol c2)
| _ -> (if Type.is_ubitvector (Term.type_of_term expr1) then
Term.mk_bvudiv [expr1; expr2]
else if Type.is_bitvector (Term.type_of_term expr1) then
Term.mk_bvsdiv [expr1; expr2]
else
Term.mk_intdiv [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_intdiv [expr1; expr2]
let type_of_intdiv t t' =
try best_int_range true Numeral.div t t' with
| Invalid_argument _ -> (
match t with
| t when Type.is_int t || Type.is_int_range t -> (
match t' with
| t when Type.is_int t || Type.is_int_range t -> Type.t_int
| _ -> raise Type_mismatch
)
| t when Type.is_ubitvector t -> (
match t' with
| t' when Type.is_ubitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_ubv 8
| 16, 16 -> Type.t_ubv 16
| 32, 32 -> Type.t_ubv 32
| 64, 64 -> Type.t_ubv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| t when Type.is_bitvector t -> (
match t' with
| t' when Type.is_bitvector t' ->
let s1 = Type.bitvectorsize t in
let s2 = Type.bitvectorsize t' in
if s1 != s2 then
raise Type_mismatch
else
(match s1,s2 with
| 8, 8 -> Type.t_bv 8
| 16, 16 -> Type.t_bv 16
| 32, 32 -> Type.t_bv 32
| 64, 64 -> Type.t_bv 64
| _, _ -> raise Type_mismatch)
| _ -> raise Type_mismatch)
| _ -> raise Type_mismatch
)
Integer division
let mk_intdiv expr1 expr2 = mk_binary eval_intdiv type_of_intdiv expr1 expr2
let eval_bvand expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| _ -> Term.mk_bvand [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_bvand [expr1; expr2]
let type_of_bvand = type_of_abv_abv_abv
Bitvector conjunction
let mk_bvand expr1 expr2 = mk_binary eval_bvand type_of_bvand expr1 expr2
let eval_bvor expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| _ -> Term.mk_bvor [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_bvor [expr1; expr2]
let type_of_bvor = type_of_abv_abv_abv
Bitvector disjunction
let mk_bvor expr1 expr2 = mk_binary eval_bvor type_of_bvor expr1 expr2
let eval_bvshl expr1 expr2 =
if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))) then
Term.mk_bvshl [expr1; expr2]
else
match Term.destruct expr1, Term.destruct expr2 with
| _ -> raise NonConstantShiftOperand
| exception Invalid_argument _ -> Term.mk_bvshl [expr1; expr2]
let type_of_bvshl = type_of_abv_ubv_abv
Bitvector left shift
let mk_bvshl expr1 expr2 = mk_binary eval_bvshl type_of_bvshl expr1 expr2
let eval_bvshr expr1 expr2 =
if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))
&& (Type.is_bitvector (Term.type_of_term expr1))) then
Term.mk_bvashr [expr1; expr2]
else if ((Term.is_bitvector expr2) && (Type.is_ubitvector (Term.type_of_term expr2))
&& (Type.is_ubitvector (Term.type_of_term expr1))) then
Term.mk_bvlshr [expr1; expr2]
else
match Term.destruct expr1, Term.destruct expr2 with
| _ -> raise NonConstantShiftOperand
| exception Invalid_argument _ -> Term.mk_bvshl [expr1; expr2]
let type_of_bvshr = type_of_abv_ubv_abv
Bitvector logical right shift
let mk_bvshr expr1 expr2 = mk_binary eval_bvshr type_of_bvshr expr1 expr2
let has_pre_vars t =
Term.state_vars_at_offset_of_term (Numeral.of_int (-1)) t
|> StateVar.StateVarSet.is_empty
|> not
let eval_eq expr1 expr2 = match expr1, expr2 with
| t, _ when t == Term.t_true -> expr2
| t, _ when t == Term.t_false -> eval_not expr2
| _, t when t == Term.t_true -> expr1
| _, t when t == Term.t_false -> eval_not expr1
| _ when Term.equal expr1 expr2
&& not (has_pre_vars expr1) && not (has_pre_vars expr2) ->
Term.t_true
| _ ->
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 =
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 =
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ -> Term.mk_eq [expr1; expr2]
| exception Invalid_argument _ -> Term.mk_eq [expr1; expr2]
let type_of_eq = type_of_a_a_bool
let mk_eq expr1 expr2 = mk_binary eval_eq type_of_eq expr1 expr2
let eval_neq expr1 expr2 = eval_not (eval_eq expr1 expr2)
let type_of_neq = type_of_a_a_bool
let mk_neq expr1 expr2 = mk_binary eval_neq type_of_neq expr1 expr2
let eval_lte expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 <=
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 <=
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvule [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvsle [expr1; expr2]
else
Term.mk_leq [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_leq [expr1; expr2]
let type_of_lte = type_of_num_num_bool
let mk_lte expr1 expr2 = mk_binary eval_lte type_of_lte expr1 expr2
let eval_lt expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 <
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 <
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvult [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvslt [expr1; expr2]
else
Term.mk_lt [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_lt [expr1; expr2]
let type_of_lt = type_of_num_num_bool
let mk_lt expr1 expr2 = mk_binary eval_lt type_of_lt expr1 expr2
let eval_gte expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 >=
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 >=
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
Term.mk_bvuge [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
Term.mk_bvsge [expr1; expr2]
else
Term.mk_geq [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_geq [expr1; expr2]
let type_of_gte = type_of_num_num_bool
let mk_gte expr1 expr2 = mk_binary eval_gte type_of_gte expr1 expr2
let eval_gt expr1 expr2 =
match Term.destruct expr1, Term.destruct expr2 with
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_numeral c1 &&
Symbol.is_numeral c2 ->
if Numeral.(Symbol.numeral_of_symbol c1 >
Symbol.numeral_of_symbol c2) then
Term.t_true
else
Term.t_false
| Term.T.Const c1, Term.T.Const c2 when
Symbol.is_decimal c1 &&
Symbol.is_decimal c2 ->
if Decimal.(Symbol.decimal_of_symbol c1 >
Symbol.decimal_of_symbol c2) then
Term.t_true
else
Term.t_false
| _ ->
(if (Type.is_ubitvector (Term.type_of_term expr1)) then
if ( Bitvector.ugt ( Term.bitvector_of_term expr1 ) ( Term.bitvector_of_term expr2 ) ) then
Term.t_true
else
Term.t_false
Term.t_true
else
Term.t_false*)
Term.mk_bvugt [expr1; expr2]
else if (Type.is_bitvector (Term.type_of_term expr1)) then
if ( Bitvector.gt ( Term.bitvector_of_term expr1 ) ( Term.bitvector_of_term expr2 ) ) then
Term.t_true
else
Term.t_false
Term.t_true
else
Term.t_false*)
Term.mk_bvsgt [expr1; expr2]
else
Term.mk_gt [expr1; expr2])
| exception Invalid_argument _ -> Term.mk_gt [expr1; expr2]
let type_of_gt = type_of_num_num_bool
let mk_gt expr1 expr2 = mk_binary eval_gt type_of_gt expr1 expr2
let eval_ite = function
| t when t == Term.t_true -> (function expr2 -> (function _ -> expr2))
| t when t == Term.t_false -> (function _ -> (function expr3 -> expr3))
| expr1 ->
(function expr2 ->
(function expr3 ->
if Term.equal expr2 expr3 then
expr2
else
(Term.mk_ite expr1 expr2 expr3)))
Type of if - then - else
If both the second and the third argument are bounded , the result
is bounded by the smaller of the two lower bound and the greater of
the upper bounds .
ite : bool - > ' a - > ' a - > ' a
If both the second and the third argument are bounded, the result
is bounded by the smaller of the two lower bound and the greater of
the upper bounds.
ite: bool -> 'a -> 'a -> 'a *)
let type_of_ite = function
| t when t = Type.t_bool ->
(function type2 -> function type3 ->
If first type is subtype of second , choose second type
if Type.check_type type2 type3 then type3 else
If second type is subtype of first , choose first type
if Type.check_type type3 type2 then type2 else
(match type2, type3 with
| s, t
when (Type.is_int_range s && Type.is_int t) ||
(Type.is_int s && Type.is_int_range t) -> Type.t_int
| s, t
when (Type.is_int_range s && Type.is_int_range t) ->
let l1, u1 = Type.bounds_of_int_range s in
let l2, u2 = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(min l1 l2) Numeral.(max u1 u2)
| _ -> raise Type_mismatch))
| _ -> (function _ -> function _ -> raise Type_mismatch)
let mk_ite expr1 expr2 expr3 =
mk_ternary eval_ite type_of_ite expr1 expr2 expr3
Type of - >
If both the arguments are bounded , the result is bounded by the
smaller of the two lower bound and the greater of the upper bounds .
- > : ' a - > ' a - > ' a
If both the arguments are bounded, the result is bounded by the
smaller of the two lower bound and the greater of the upper bounds.
->: 'a -> 'a -> 'a *)
let type_of_arrow type1 type2 =
(match type1, type2 with
| s, t
when (Type.is_int_range s && Type.is_int_range t) ->
let l1, u1 = Type.bounds_of_int_range s in
let l2, u2 = Type.bounds_of_int_range t in
Type.mk_int_range Numeral.(min l1 l2) Numeral.(max u1 u2)
| _ -> type_of_a_a_a type1 type2)
let mk_arrow expr1 expr2 =
let res_type =
type_of_arrow expr1.expr_type expr2.expr_type
in
{ expr_init = expr1.expr_init;
expr_step = expr2.expr_step;
expr_type = res_type }
We do n't need to abstract the RHS because the AST normalization pass
already has .
already has. *)
let mk_pre ({ expr_init; expr_step } as expr) =
if Term.equal expr_init expr_step then
match expr_init with
| t when (t == Term.t_true
|| t == Term.t_false
|| (Term.is_free_var t && Term.free_var_of_term t |> Var.is_const_state_var)
|| (match Term.destruct t with
| Term.T.Const c1 when Symbol.is_numeral c1 || Symbol.is_decimal c1 -> true
| _ -> false))
-> expr
| t when Term.is_free_var t
&& Term.free_var_of_term t |> Var.is_state_var_instance
&& Numeral.(Var.offset_of_state_var_instance (Term.free_var_of_term t) = base_offset) ->
let pt = Term.bump_state Numeral.(- one) t in
{ expr with expr_init = pt; expr_step = pt }
| _ -> assert false
else assert false
let mk_pre_with_context mk_abs_for_expr mk_lhs_term ctx unguarded
({ expr_init; expr_step; expr_type } as expr) =
let abs_pre () =
let expr_type = Type.generalize expr_type in
let expr = { expr with expr_type } in
let abs, ctx = mk_abs_for_expr ctx expr in
let abs_t = mk_lhs_term abs in
{ expr_init = abs_t;
expr_step = abs_t;
expr_type }, ctx
in
if not unguarded &&
Term.equal expr_init expr_step then
match expr_init with
| t when
(t == Term.t_true ||
t == Term.t_false ||
(Term.is_free_var t &&
Term.free_var_of_term t |> Var.is_const_state_var) ||
(match Term.destruct t with
| Term.T.Const c1 when
Symbol.is_numeral c1 || Symbol.is_decimal c1 -> true
| _ -> false)) ->
expr, ctx
| t when Term.is_free_var t &&
Term.free_var_of_term t |> Var.is_state_var_instance &&
Numeral.(Var.offset_of_state_var_instance (Term.free_var_of_term t) =
base_offset) ->
let pt = Term.bump_state Numeral.(- one) t in
{ expr with expr_init = pt; expr_step = pt }, ctx
| _ -> abs_pre ()
abs_pre ()
let eval_select = Term.mk_select
let type_of_select = function
First argument must be an array type
| s when Type.is_array s ->
(function t ->
Second argument must match index type of array
if Type.check_type (Type.index_type_of_array s) t then
Type.elem_type_of_array s
else
raise Type_mismatch)
| _ -> raise Type_mismatch
let mk_select expr1 expr2 =
mk_binary eval_select type_of_select expr1 expr2
let mk_array expr1 expr2 =
let type_of_array t1 t2 = Type.mk_array t1 t2 in
mk_binary (fun x _ -> x) type_of_array expr1 expr2
let eval_store = Term.mk_store
let type_of_store = function
First argument must be an array type
| s when Type.is_array s ->
(fun i v ->
Second argument must match index type of array
if Type.check_type i (Type.index_type_of_array s) &&
Type.check_type (Type.elem_type_of_array s) v
then
s
else
raise Type_mismatch)
| _ ->
raise Type_mismatch
let mk_store expr1 expr2 expr3 =
Format.eprintf " mk_store % a:%a [ % a , % a ] % a:%a % a:%a@. "
( pp_print_lustre_expr false ) expr1
Type.pp_print_type ( type_of_lustre_expr expr1 )
Type.pp_print_type ( Type.elem_type_of_array ( type_of_lustre_expr expr1 ) )
( pp_print_lustre_expr false ) expr2
Type.pp_print_type ( type_of_lustre_expr expr2 )
Type.pp_print_type ( type_of_lustre_expr expr3 ) ;
mk_ternary eval_store type_of_store expr1 expr2 expr3
let is_store e = Term.is_store e.expr_init && Term.is_store e.expr_step
let is_select e = Term.is_select e.expr_init && Term.is_select e.expr_step
let is_select_array_var e =
is_select e &&
try
ignore (Term.indexes_and_var_of_select e.expr_init);
ignore (Term.indexes_and_var_of_select e.expr_step);
true
with Invalid_argument _ -> false
let var_of_array_select e =
let v1, _ = Term.indexes_and_var_of_select e.expr_init in
let v2, _ = Term.indexes_and_var_of_select e.expr_step in
if not (Var.equal_vars v1 v2) then invalid_arg ("var_of_array_select");
v1
let indexes_and_var_of_array_select e =
let v1, ixes1 = Term.indexes_and_var_of_select e.expr_init in
let v2, ixes2 = Term.indexes_and_var_of_select e.expr_step in
if not (Var.equal_vars v1 v2) then
invalid_arg ("indexes_and_var_of_array_select.var");
if not (List.for_all2 Term.equal ixes1 ixes2) then
invalid_arg ("indexes_and_var_of_array_select.indexes");
(v1, ixes1)
let mk_let_cur substs ({ expr_init; expr_step } as expr) =
let substs_init, substs_step =
let i, s =
List.fold_left
(fun (substs_init, substs_step) (sv, { expr_init; expr_step }) ->
((base_var_of_state_var base_offset sv, expr_init) :: substs_init,
(cur_var_of_state_var cur_offset sv, expr_step) :: substs_step))
([], [])
substs
in
List.rev i, List.rev s
in
{ expr with
expr_init = Term.mk_let substs_init expr_init;
expr_step = Term.mk_let substs_step expr_step }
let mk_let_pre substs ({ expr_init; expr_step } as expr) =
let substs_init, substs_step =
let i, s =
List.fold_left
(fun (substs_init, substs_step) (sv, { expr_init; expr_step }) ->
((pre_base_var_of_state_var base_offset sv, expr_init) :: substs_init,
(pre_var_of_state_var cur_offset sv, expr_step) :: substs_step))
([], [])
substs
in
List.rev i, List.rev s
in
let subst_has_arrays =
List.exists (fun (v, _) -> Var.type_of_var v |> Type.is_array) in
let expr_init =
if subst_has_arrays substs_init then Term.apply_subst substs_init expr_init
else Term.mk_let substs_init expr_init in
let expr_step =
if subst_has_arrays substs_step then Term.apply_subst substs_step expr_step
else Term.mk_let substs_step expr_step in
{ expr with expr_init; expr_step}
let mk_int_expr n = Term.mk_num n
let mk_of_expr ?as_type expr =
let expr_type = match as_type with
| Some ty -> ty
| None -> Term.type_of_term expr
in
{ expr_init = expr;
expr_step = expr;
expr_type }
let is_numeral = Term.is_numeral
let numeral_of_expr = Term.numeral_of_term
let unsafe_term_of_expr e = (e : Term.t)
let unsafe_expr_of_term t = t
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
|
0cca168883585a3e211c95fd29b9c0d746246a8a8e8fbf3c946d3bfe1dd27eac | RDTK/generator | aspects.lisp | aspects.lisp --- Aspect extensions used in the module .
;;;;
Copyright ( C ) 2018 - 2022 Jan Moringen
;;;;
Author : < >
(cl:in-package #:build-generator.deployment.build)
(defun step-name (aspect)
(format nil "~{~A~^.~}" (reverse (model:ancestor-names aspect))))
(defmethod aspects::step-constraints ((aspect aspects::aspect-builder-defining-mixin)
(phase (eql 'aspects::build))
(step step))
(when-let ((builder-class (builder-class step)))
(let* ((variable (let ((*package* (find-package '#:keyword)))
(symbolicate '#:aspect.builder-constraints.
builder-class)))
(constraints/raw (var:value aspect variable nil))
(constraints (mapcar #'aspects::parse-constraint constraints/raw)))
(log:debug "~@<Constraints for ~A in ~A~:@_~
~/aspects::format-constraints/~@:>"
step variable constraints)
constraints)))
(defmethod aspects:extend! ((aspect list)
(spec t)
(output project-steps)
(target (eql :build)))
;; Apply aspects, respecting declared ordering. Translate builder
;; ordering constraints into step dependencies.
(let+ ((aspects::*step-constraints* '())
(aspects (util:sort-with-partial-order
(copy-list aspect) #'aspects:aspect<)))
;; Methods on `extend!' add entries to `*step-constraints*' and
;; call (add-step STEP OUTPUT).
(reduce (lambda (output aspect)
(aspects:extend! aspect spec output target))
aspects :initial-value output)
(let ((constraints (aspects::constraints-table 'aspects::build))
(steps (steps output)))
(when steps
(log:debug "~@<~@(~A~)er constraint~P:~@:_~
~@<~{• ~{~
~A ~A:~A ~@:_~
~2@T~@<~/build-generator.model.aspects:format-constraints/~@:>~
~}~^~@:_~}~@:>~
~@:>"
'aspects::build (hash-table-count constraints)
(hash-table-alist constraints))
(map nil (lambda (step)
(setf (dependencies step)
(remove-if-not (rcurry #'aspects::step< step constraints)
steps)))
steps))))
output)
(defmethod aspects:extend! ((aspect t)
(spec t)
(output project-steps)
(target (eql :build)))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-builder-defining-mixin)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (aspects:extend! aspect spec 'string :command))
TODO ( aspects : tag aspect ) would be better
(tag (or (find-symbol (subseq (symbol-name name) (length "ASPECT-"))
'#:build-generator.model.aspects)
(error "Something is wrong with the aspect tag of ~A" aspect)))
(step (make-step (step-name aspect) command :builder-class tag)))
(aspects::register-constraints aspect 'aspects::build step tag '())
(add-step step output))
output)
;;; Individual aspect classes
(defmethod aspects:extend! ((aspect aspects::aspect-archive)
(spec t)
(output project-steps)
(target (eql :build)))
(let* ((command (aspects:extend! aspect spec 'string :command))
(step (make-step (step-name aspect) command :early? t)))
(aspects::register-constraints aspect 'aspects::build step 'aspects::archive '((:before t)))
(add-step step output))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-sloccount)
(spec t)
(output project-steps)
(target (eql :build)))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-git)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (with-output-to-string (stream)
(aspects:extend! aspect spec stream :command)
(aspects:extend! aspect spec stream :sub-directory-command)))
(step (unless (emptyp command)
(make-step (step-name aspect) command :early? t
:builder-class 'aspects::git))))
(aspects::register-constraints aspect 'aspects::build step 'aspects::git '())
(add-step step output))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-mercurial)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (with-output-to-string (stream)
(aspects:extend! aspect spec stream :command)
(aspects:extend! aspect spec stream :sub-directory-command)))
(step (unless (emptyp command)
(make-step (step-name aspect) command :early? t
:builder-class 'aspects::mercurial))))
(aspects::register-constraints aspect 'aspects::build step 'aspects::mercurial '())
(add-step step output))
output)
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/src/deployment/build/aspects.lisp | lisp |
Apply aspects, respecting declared ordering. Translate builder
ordering constraints into step dependencies.
Methods on `extend!' add entries to `*step-constraints*' and
call (add-step STEP OUTPUT).
Individual aspect classes | aspects.lisp --- Aspect extensions used in the module .
Copyright ( C ) 2018 - 2022 Jan Moringen
Author : < >
(cl:in-package #:build-generator.deployment.build)
(defun step-name (aspect)
(format nil "~{~A~^.~}" (reverse (model:ancestor-names aspect))))
(defmethod aspects::step-constraints ((aspect aspects::aspect-builder-defining-mixin)
(phase (eql 'aspects::build))
(step step))
(when-let ((builder-class (builder-class step)))
(let* ((variable (let ((*package* (find-package '#:keyword)))
(symbolicate '#:aspect.builder-constraints.
builder-class)))
(constraints/raw (var:value aspect variable nil))
(constraints (mapcar #'aspects::parse-constraint constraints/raw)))
(log:debug "~@<Constraints for ~A in ~A~:@_~
~/aspects::format-constraints/~@:>"
step variable constraints)
constraints)))
(defmethod aspects:extend! ((aspect list)
(spec t)
(output project-steps)
(target (eql :build)))
(let+ ((aspects::*step-constraints* '())
(aspects (util:sort-with-partial-order
(copy-list aspect) #'aspects:aspect<)))
(reduce (lambda (output aspect)
(aspects:extend! aspect spec output target))
aspects :initial-value output)
(let ((constraints (aspects::constraints-table 'aspects::build))
(steps (steps output)))
(when steps
(log:debug "~@<~@(~A~)er constraint~P:~@:_~
~@<~{• ~{~
~A ~A:~A ~@:_~
~2@T~@<~/build-generator.model.aspects:format-constraints/~@:>~
~}~^~@:_~}~@:>~
~@:>"
'aspects::build (hash-table-count constraints)
(hash-table-alist constraints))
(map nil (lambda (step)
(setf (dependencies step)
(remove-if-not (rcurry #'aspects::step< step constraints)
steps)))
steps))))
output)
(defmethod aspects:extend! ((aspect t)
(spec t)
(output project-steps)
(target (eql :build)))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-builder-defining-mixin)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (aspects:extend! aspect spec 'string :command))
TODO ( aspects : tag aspect ) would be better
(tag (or (find-symbol (subseq (symbol-name name) (length "ASPECT-"))
'#:build-generator.model.aspects)
(error "Something is wrong with the aspect tag of ~A" aspect)))
(step (make-step (step-name aspect) command :builder-class tag)))
(aspects::register-constraints aspect 'aspects::build step tag '())
(add-step step output))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-archive)
(spec t)
(output project-steps)
(target (eql :build)))
(let* ((command (aspects:extend! aspect spec 'string :command))
(step (make-step (step-name aspect) command :early? t)))
(aspects::register-constraints aspect 'aspects::build step 'aspects::archive '((:before t)))
(add-step step output))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-sloccount)
(spec t)
(output project-steps)
(target (eql :build)))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-git)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (with-output-to-string (stream)
(aspects:extend! aspect spec stream :command)
(aspects:extend! aspect spec stream :sub-directory-command)))
(step (unless (emptyp command)
(make-step (step-name aspect) command :early? t
:builder-class 'aspects::git))))
(aspects::register-constraints aspect 'aspects::build step 'aspects::git '())
(add-step step output))
output)
(defmethod aspects:extend! ((aspect aspects::aspect-mercurial)
(spec t)
(output project-steps)
(target (eql :build)))
(when-let* ((command (with-output-to-string (stream)
(aspects:extend! aspect spec stream :command)
(aspects:extend! aspect spec stream :sub-directory-command)))
(step (unless (emptyp command)
(make-step (step-name aspect) command :early? t
:builder-class 'aspects::mercurial))))
(aspects::register-constraints aspect 'aspects::build step 'aspects::mercurial '())
(add-step step output))
output)
|
574273f14f69ad177d9e89f3a3c187b39c07f555568c582b01bae765516f6cc1 | helins/mprop.cljc | mprop.cljc | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns helins.mprop
"Multiplexing `test.check` property and tracking failure.
See README for overview."
{:author "Adam Helinski"}
(:refer-clojure :exclude [and])
(:require [clojure.core]
[clojure.test.check.clojure-test :as TC.ct]
[clojure.test.check.results :as TC.result])
#?(:cljs (:require-macros [helins.mprop :refer [and
check
deftest
mult]])))
(declare fail)
;;;;;;;;;; Defining tests
#?(:clj (let [get-env (fn [k default]
(if-some [x (not-empty (System/getenv k))]
(try
(Long/parseLong x)
(catch Throwable e
(throw (ex-info (str "While parsing env variable: "
k)
{::env-var k}
e))))
default))]
(def max-size
"Maximum size used by [[deftest]]. Can be set using the `MPROP_MAX_SIZE` env variable.
Default value is 200."
(get-env "MPROP_MAX_SIZE"
200))
(def num-tests
"Number of tests used by [[deftest]]. Can be set using the `MPROP_NUM_TESTS` env variable.
Default value is 100."
(get-env "MPROP_NUM_TESTS"
100))))
#?(:clj (defmacro deftest
"Like `clojure.test.check.clojure-test/defspec`.
Difference is that the number of tests and maximum size can be easily configured
and calibrated at the level of the whole test suite.
`option+` is a map as accepted by `defspec`, it can notably hold `:max-size` and
`:num-tests`.
Most of the time, it is not productive fixing absolute values. During dev, number of tests
and maximum size can be kept low in order to gain a fast feedback on what is going on.
During actual testing, those values can be set a lot higher.
For altering the base values, see [[max-size]] and [[num-tests]]. Each test can be
calibrated against those base values. `option+` also accepts:
| Key | Value |
|---|---|
| `:ratio-num` | Multiplies the base [[num-tests]] value |
| `:ratio-size` | Multiplies the base [[max-size]] value |
For instance, a test that runs 10 times more with half the maximum size:
```clojure
(deftest foo
{:ratio-num 10
:ratio-size 0.5}
some-property)
```"
([sym prop]
`(deftest ~sym
nil
~prop))
([sym option+ prop]
`(TC.ct/defspec ~sym
~(-> option+
(update :max-size
#(or %
(* max-size
(or (:ratio-size option+)
1))))
(update :num-tests
#(or %
(* num-tests
(or (:ratio-num option+)
1)))))
~prop))))
Testing more than one assertion
(let [-and (fn -and [[form & form-2+]]
(if form-2+
`(let [x# ~form]
(if (TC.result/pass? x#)
~(-and form-2+)
x#))
form))]
(defmacro and
"Like Clojure's `and` but an item is considered truthy if it passes `clojure.test.check.results/pass?`.
Great match for [[check]] as it allows for testing several assertions, even nested one, while keepin track
of where failure happens."
[& form+]
(if (seq form+)
(-and form+)
true)))
(defn ^:no-doc -check
;; Used by [[check]], must be kept public.
[beacon f]
(try
(let [x (f)]
(if (TC.result/pass? x)
x
(fail beacon
x)))
(catch #?(:clj Throwable
:cljs :default) e
(fail beacon
e))))
(defmacro check
"Executes form.
Any failure or thrown exception is wrapped in an object that returns false on `clojure.test.check.results/pass?` with
the following result data map attached:
| Key | Value |
|---|---|
| `:mprop/path` | List of `beacon`s, contains more than one if checks were nested and shows exactly where failure happened |
| `:mprop/value` | Value returned by `form` |
Usually, checks are used with [[and]]. A `beacon` can be any value the user deems useful (often a human-readable string).
For example (`and` being [[and]] from this namespace):
```clojure
(and (check \"Some test\"
(= 4 (+ 2 2)))
(check \"Another test\"
(= 3 (inc 1))))
```"
[beacon form]
`(-check ~beacon
(fn [] ~form)))
(defn fail
"Used by [[check]].
More rarely, can be used to return an explicit failure."
[beacon failure]
(let [result-upstream (TC.result/result-data failure)
path (:mprop/path result-upstream)
result {:mprop/path (cons beacon
path)
:mprop/value (if path
(:mprop/value result-upstream)
failure)}]
(reify TC.result/Result
(pass? [_]
false)
(result-data [_]
result))))
(defmacro mult
"Very common, sugar for using [[check]] with [[and]].
Short for \"multiplex\".
Replicating example in [[check]]:
```clojure
(mult \"Some assertion\"
(= 4 (+ 2 2))
\"Another assertion\"
(= 3 (inc 1)))
```"
[& check+]
(assert (even? (count check+)))
`(helins.mprop/and ~@(map (fn [[beacon form]]
`(check ~beacon
~form))
(partition 2
check+))))
| null | https://raw.githubusercontent.com/helins/mprop.cljc/1d7d7e1e06bc2c45e6dc82c0ab83ebbd7e8271fc/src/main/helins/mprop.cljc | clojure | Defining tests
Used by [[check]], must be kept public. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns helins.mprop
"Multiplexing `test.check` property and tracking failure.
See README for overview."
{:author "Adam Helinski"}
(:refer-clojure :exclude [and])
(:require [clojure.core]
[clojure.test.check.clojure-test :as TC.ct]
[clojure.test.check.results :as TC.result])
#?(:cljs (:require-macros [helins.mprop :refer [and
check
deftest
mult]])))
(declare fail)
#?(:clj (let [get-env (fn [k default]
(if-some [x (not-empty (System/getenv k))]
(try
(Long/parseLong x)
(catch Throwable e
(throw (ex-info (str "While parsing env variable: "
k)
{::env-var k}
e))))
default))]
(def max-size
"Maximum size used by [[deftest]]. Can be set using the `MPROP_MAX_SIZE` env variable.
Default value is 200."
(get-env "MPROP_MAX_SIZE"
200))
(def num-tests
"Number of tests used by [[deftest]]. Can be set using the `MPROP_NUM_TESTS` env variable.
Default value is 100."
(get-env "MPROP_NUM_TESTS"
100))))
#?(:clj (defmacro deftest
"Like `clojure.test.check.clojure-test/defspec`.
Difference is that the number of tests and maximum size can be easily configured
and calibrated at the level of the whole test suite.
`option+` is a map as accepted by `defspec`, it can notably hold `:max-size` and
`:num-tests`.
Most of the time, it is not productive fixing absolute values. During dev, number of tests
and maximum size can be kept low in order to gain a fast feedback on what is going on.
During actual testing, those values can be set a lot higher.
For altering the base values, see [[max-size]] and [[num-tests]]. Each test can be
calibrated against those base values. `option+` also accepts:
| Key | Value |
|---|---|
| `:ratio-num` | Multiplies the base [[num-tests]] value |
| `:ratio-size` | Multiplies the base [[max-size]] value |
For instance, a test that runs 10 times more with half the maximum size:
```clojure
(deftest foo
{:ratio-num 10
:ratio-size 0.5}
some-property)
```"
([sym prop]
`(deftest ~sym
nil
~prop))
([sym option+ prop]
`(TC.ct/defspec ~sym
~(-> option+
(update :max-size
#(or %
(* max-size
(or (:ratio-size option+)
1))))
(update :num-tests
#(or %
(* num-tests
(or (:ratio-num option+)
1)))))
~prop))))
Testing more than one assertion
(let [-and (fn -and [[form & form-2+]]
(if form-2+
`(let [x# ~form]
(if (TC.result/pass? x#)
~(-and form-2+)
x#))
form))]
(defmacro and
"Like Clojure's `and` but an item is considered truthy if it passes `clojure.test.check.results/pass?`.
Great match for [[check]] as it allows for testing several assertions, even nested one, while keepin track
of where failure happens."
[& form+]
(if (seq form+)
(-and form+)
true)))
(defn ^:no-doc -check
[beacon f]
(try
(let [x (f)]
(if (TC.result/pass? x)
x
(fail beacon
x)))
(catch #?(:clj Throwable
:cljs :default) e
(fail beacon
e))))
(defmacro check
"Executes form.
Any failure or thrown exception is wrapped in an object that returns false on `clojure.test.check.results/pass?` with
the following result data map attached:
| Key | Value |
|---|---|
| `:mprop/path` | List of `beacon`s, contains more than one if checks were nested and shows exactly where failure happened |
| `:mprop/value` | Value returned by `form` |
Usually, checks are used with [[and]]. A `beacon` can be any value the user deems useful (often a human-readable string).
For example (`and` being [[and]] from this namespace):
```clojure
(and (check \"Some test\"
(= 4 (+ 2 2)))
(check \"Another test\"
(= 3 (inc 1))))
```"
[beacon form]
`(-check ~beacon
(fn [] ~form)))
(defn fail
"Used by [[check]].
More rarely, can be used to return an explicit failure."
[beacon failure]
(let [result-upstream (TC.result/result-data failure)
path (:mprop/path result-upstream)
result {:mprop/path (cons beacon
path)
:mprop/value (if path
(:mprop/value result-upstream)
failure)}]
(reify TC.result/Result
(pass? [_]
false)
(result-data [_]
result))))
(defmacro mult
"Very common, sugar for using [[check]] with [[and]].
Short for \"multiplex\".
Replicating example in [[check]]:
```clojure
(mult \"Some assertion\"
(= 4 (+ 2 2))
\"Another assertion\"
(= 3 (inc 1)))
```"
[& check+]
(assert (even? (count check+)))
`(helins.mprop/and ~@(map (fn [[beacon form]]
`(check ~beacon
~form))
(partition 2
check+))))
|
cee7316b637eefa4d29edaeaf7abc9a3b26c74517575178c02e99fc0676fdb76 | metosin/testit | facts_example.clj | (ns example.facts-example
(:require [clojure.test :refer :all]
[testit.core :refer :all]))
(deftest group-multiple-assertions
(facts "simple match tests"
(+ 1 2) => 3
(* 21 2) => 42
(+ 623 714) => 1337))
| null | https://raw.githubusercontent.com/metosin/testit/85c9cfc9629f44d13e9b16fe25175235ae1e39e1/examples/example/facts_example.clj | clojure | (ns example.facts-example
(:require [clojure.test :refer :all]
[testit.core :refer :all]))
(deftest group-multiple-assertions
(facts "simple match tests"
(+ 1 2) => 3
(* 21 2) => 42
(+ 623 714) => 1337))
| |
c0e7354f25487dc7c02d9eff8e251ef74cbff7d5ecfa03036096dad012ffcad4 | mpickering/apply-refact | Default43.hs | no = elem 1 [] : [] | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default43.hs | haskell | no = elem 1 [] : [] | |
3acc3e79f71011dbcc8db9f65080079b7c6d51c7384b758383914875bda24ab1 | phuhl/linux_notification_center | Glade.hs | {-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module NotificationCenter.Glade where
import Data.String.Here.Uninterpolated (hereFile)
glade =
[hereFile|notification_center.glade|]
| null | https://raw.githubusercontent.com/phuhl/linux_notification_center/640ce0fc05a68f2c28be3d9f27fe73516d4332f9/src/NotificationCenter/Glade.hs | haskell | # LANGUAGE QuasiQuotes, OverloadedStrings # |
module NotificationCenter.Glade where
import Data.String.Here.Uninterpolated (hereFile)
glade =
[hereFile|notification_center.glade|]
|
a2568a70cba3085623e86c720a9d4e6055b3368bae9cc3838cc2957ec5f58243 | jumarko/web-development-with-clojure | layout.clj | ;---
Excerpted from " Web Development with Clojure , Second Edition " ,
published by The Pragmatic Bookshelf .
Copyrights apply to this code . It may not be used to create training material ,
; courses, books, articles, and the like. Contact us if you are in doubt.
; We make no guarantees that this code is fit for any purpose.
; Visit for more book information.
;---
(ns picture-gallery.layout
(:require [selmer.parser :as parser]
[selmer.filters :as filters]
[markdown.core :refer [md-to-html-string]]
[ring.util.http-response :refer [content-type ok]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]))
(declare ^:dynamic *identity*)
(declare ^:dynamic *app-context*)
(parser/set-resource-path! (clojure.java.io/resource "templates"))
(parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field)))
(filters/add-filter! :markdown (fn [content] [:safe (md-to-html-string content)]))
(defn render
"renders the HTML template located relative to resources/templates"
[template & [params]]
(content-type
(ok
(parser/render-file
template
(assoc params
:page template
:csrf-token *anti-forgery-token*
:servlet-context *app-context*
:identity *identity*)))
"text/html; charset=utf-8"))
(defn error-page
"error-details should be a map containing the following keys:
:status - error status
:title - error title (optional)
:message - detailed error message (optional)
returns a response map with the error page as the body
and the status specified by the status key"
[error-details]
{:status (:status error-details)
:headers {"Content-Type" "text/html; charset=utf-8"}
:body (parser/render-file "error.html" error-details)})
| null | https://raw.githubusercontent.com/jumarko/web-development-with-clojure/dfff6e40c76b64e9fcd440d80c7aa29809601b6b/code/picture-gallery-colors/src/clj/picture_gallery/layout.clj | clojure | ---
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
--- | Excerpted from " Web Development with Clojure , Second Edition " ,
published by The Pragmatic Bookshelf .
Copyrights apply to this code . It may not be used to create training material ,
(ns picture-gallery.layout
(:require [selmer.parser :as parser]
[selmer.filters :as filters]
[markdown.core :refer [md-to-html-string]]
[ring.util.http-response :refer [content-type ok]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]))
(declare ^:dynamic *identity*)
(declare ^:dynamic *app-context*)
(parser/set-resource-path! (clojure.java.io/resource "templates"))
(parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field)))
(filters/add-filter! :markdown (fn [content] [:safe (md-to-html-string content)]))
(defn render
"renders the HTML template located relative to resources/templates"
[template & [params]]
(content-type
(ok
(parser/render-file
template
(assoc params
:page template
:csrf-token *anti-forgery-token*
:servlet-context *app-context*
:identity *identity*)))
"text/html; charset=utf-8"))
(defn error-page
"error-details should be a map containing the following keys:
:status - error status
:title - error title (optional)
:message - detailed error message (optional)
returns a response map with the error page as the body
and the status specified by the status key"
[error-details]
{:status (:status error-details)
:headers {"Content-Type" "text/html; charset=utf-8"}
:body (parser/render-file "error.html" error-details)})
|
5a9ac96f75b0742950130d17faadff7d80de1c42c74e67a8764236225b6651e1 | erlang-ls/erlang_ls | code_navigation.erl | -module(code_navigation).
-behaviour(behaviour_a).
-wildattribute(a).
-export([ function_a/0, function_b/0, function_g/1, function_j/0, 'PascalCaseFunction'/1, function_mb/0 ]).
%% behaviour_a callbacks
-export([ callback_a/0 ]).
-export_type([ type_a/0 ]).
-import(code_navigation_extra, [ do/1 ]).
-include("transitive.hrl").
-include("code_navigation.hrl").
-include_lib("code_navigation/include/code_navigation.hrl").
-include_lib("stdlib/include/assert.hrl").
-record(record_a, {field_a, field_b, 'Field C'}).
-define(MACRO_A, macro_a).
-define(MACRO_A(X), erlang:display(X)).
function_a() ->
function_b(),
#record_a{}.
function_b() ->
?MACRO_A.
callback_a() ->
ok.
function_c() ->
code_navigation_extra:do(test),
A = #record_a{ field_a = a },
_X = A#record_a.field_a, _Y = A#record_a.field_a,
length([1, 2, 3]).
-type type_a() :: any().
function_d() ->
?MACRO_A(d).
function_e() ->
?assertEqual(2.0, 4/2).
-define(macro_A, macro_A).
function_f() ->
?macro_A.
function_g(X) ->
F = fun function_b/0,
G = {fun code_navigation_extra:do/1, X#included_record_a.field_b, X#'PascalCaseRecord'.'Field #1'},
{?INCLUDED_MACRO_A, #included_record_a{included_field_a = a}, F, G}.
-spec function_h() -> type_a() | undefined_type_a() | file:fd().
function_h() ->
function_i().
-ifdef(foo).
function_i() -> one.
-else.
function_i() -> two.
-endif.
%% @doc Such a wonderful function.
-spec function_j() -> pos_integer().
function_j() ->
53.
[ # 283 ] Macro as function name crashes parser
?macro_A() -> ok.
[ # 333 ] Record field accessors assumed to be atoms
function_k() ->
X#included_record_a.?MACRO_A,
<<"foo:">>.
[ # 314 ] Add ' _ ' to unused variable
function_l(X, Y) ->
A = X,
Y.
[ # 485 ] atoms referencing a module
function_m(code_navigation_types) ->
code_navigation_extra, 'Code.Navigation.Elixirish',
function_m(code_navigation_extra).
[ # 386 ] go to definition of import by module
function_n() ->
do(4).
%% atom highlighting and completion includes record fields
function_o() ->
{field_a, incl}.
%% quoted atoms
-spec 'PascalCaseFunction'(T) -> 'Code.Navigation.Elixirish':'Type'(T).
'PascalCaseFunction'(R) ->
_ = R#record_a.'Field C',
F = fun 'Code.Navigation.Elixirish':do/1,
F('Atom with whitespaces, "double quotes" and even some \'single quotes\'').
function_p(Foo) ->
Bar = Foo,
_Baz = Bar;
function_p(Foo) ->
_Bar = Foo,
_Baz = Foo.
%% [#1052] ?MODULE macro as record name
-record(?MODULE, {field_a, field_b}).
-spec function_q() -> {#?MODULE{field_a :: integer()}, any()}.
function_q() ->
X = #?MODULE{},
{X#?MODULE{field_a = 42}, X#?MODULE.field_a}.
-define(MACRO_B, macro_b).
macro_b(_X, _Y) ->
ok.
function_mb() ->
?MACRO_B(m, b).
code_navigation() -> code_navigation.
code_navigation(X) -> X.
multiple_instances_same_file() -> {code_navigation, [simple_list], "abc"}.
code_navigation_extra(X, Y, Z) -> [code_navigation_extra, X, Y, Z].
multiple_instances_diff_file() -> code_navigation_extra.
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/4ad07492c2f577da4a1fbd79877036f820d9e2c3/apps/els_lsp/priv/code_navigation/src/code_navigation.erl | erlang | behaviour_a callbacks
@doc Such a wonderful function.
atom highlighting and completion includes record fields
quoted atoms
[#1052] ?MODULE macro as record name | -module(code_navigation).
-behaviour(behaviour_a).
-wildattribute(a).
-export([ function_a/0, function_b/0, function_g/1, function_j/0, 'PascalCaseFunction'/1, function_mb/0 ]).
-export([ callback_a/0 ]).
-export_type([ type_a/0 ]).
-import(code_navigation_extra, [ do/1 ]).
-include("transitive.hrl").
-include("code_navigation.hrl").
-include_lib("code_navigation/include/code_navigation.hrl").
-include_lib("stdlib/include/assert.hrl").
-record(record_a, {field_a, field_b, 'Field C'}).
-define(MACRO_A, macro_a).
-define(MACRO_A(X), erlang:display(X)).
function_a() ->
function_b(),
#record_a{}.
function_b() ->
?MACRO_A.
callback_a() ->
ok.
function_c() ->
code_navigation_extra:do(test),
A = #record_a{ field_a = a },
_X = A#record_a.field_a, _Y = A#record_a.field_a,
length([1, 2, 3]).
-type type_a() :: any().
function_d() ->
?MACRO_A(d).
function_e() ->
?assertEqual(2.0, 4/2).
-define(macro_A, macro_A).
function_f() ->
?macro_A.
function_g(X) ->
F = fun function_b/0,
G = {fun code_navigation_extra:do/1, X#included_record_a.field_b, X#'PascalCaseRecord'.'Field #1'},
{?INCLUDED_MACRO_A, #included_record_a{included_field_a = a}, F, G}.
-spec function_h() -> type_a() | undefined_type_a() | file:fd().
function_h() ->
function_i().
-ifdef(foo).
function_i() -> one.
-else.
function_i() -> two.
-endif.
-spec function_j() -> pos_integer().
function_j() ->
53.
[ # 283 ] Macro as function name crashes parser
?macro_A() -> ok.
[ # 333 ] Record field accessors assumed to be atoms
function_k() ->
X#included_record_a.?MACRO_A,
<<"foo:">>.
[ # 314 ] Add ' _ ' to unused variable
function_l(X, Y) ->
A = X,
Y.
[ # 485 ] atoms referencing a module
function_m(code_navigation_types) ->
code_navigation_extra, 'Code.Navigation.Elixirish',
function_m(code_navigation_extra).
[ # 386 ] go to definition of import by module
function_n() ->
do(4).
function_o() ->
{field_a, incl}.
-spec 'PascalCaseFunction'(T) -> 'Code.Navigation.Elixirish':'Type'(T).
'PascalCaseFunction'(R) ->
_ = R#record_a.'Field C',
F = fun 'Code.Navigation.Elixirish':do/1,
F('Atom with whitespaces, "double quotes" and even some \'single quotes\'').
function_p(Foo) ->
Bar = Foo,
_Baz = Bar;
function_p(Foo) ->
_Bar = Foo,
_Baz = Foo.
-record(?MODULE, {field_a, field_b}).
-spec function_q() -> {#?MODULE{field_a :: integer()}, any()}.
function_q() ->
X = #?MODULE{},
{X#?MODULE{field_a = 42}, X#?MODULE.field_a}.
-define(MACRO_B, macro_b).
macro_b(_X, _Y) ->
ok.
function_mb() ->
?MACRO_B(m, b).
code_navigation() -> code_navigation.
code_navigation(X) -> X.
multiple_instances_same_file() -> {code_navigation, [simple_list], "abc"}.
code_navigation_extra(X, Y, Z) -> [code_navigation_extra, X, Y, Z].
multiple_instances_diff_file() -> code_navigation_extra.
|
73cf6f211b093b6282105337ef41a8f62bbfad0af3e69c67971738c2adee2c84 | manuel-serrano/hop | reflect.scm | ;*=====================================================================*/
* serrano / prgm / project / hop / hop / hopscript / reflect.scm * /
;* ------------------------------------------------------------- */
* Author : * /
;* Creation : Wed Dec 5 22:00:24 2018 */
* Last change : Sun Mar 1 11:17:27 2020 ( serrano ) * /
* Copyright : 2018 - 20 * /
;* ------------------------------------------------------------- */
* Native Bigloo support of JavaScript REFLECT object . * /
;* ------------------------------------------------------------- */
* -US/docs/Web/JavaScript/ * /
;* Reference/Global_Objects/Reflect */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __hopscript_reflect
(include "../nodejs/nodejs_debug.sch")
(library hop)
(include "types.sch" "stringliteral.sch")
(import __hopscript_types
__hopscript_arithmetic
__hopscript_lib
__hopscript_object
__hopscript_function
__hopscript_property
__hopscript_private
__hopscript_public
__hopscript_regexp
__hopscript_array
__hopscript_error
__hopscript_worker
__hopscript_spawn)
(export (js-init-reflect! ::JsGlobalObject)))
;*---------------------------------------------------------------------*/
;* &begin! */
;*---------------------------------------------------------------------*/
(define __js_strings (&begin!))
;*---------------------------------------------------------------------*/
;* js-init-reflect! ... */
;*---------------------------------------------------------------------*/
(define (js-init-reflect! %this::JsGlobalObject)
(unless (vector? __js_strings) (set! __js_strings (&init!)))
(define js-reflect
(instantiateJsObject
(__proto__ (js-object-proto %this))
(elements ($create-vector 14))))
(define (js-reflect-apply this target thisarg argarray)
(js-apply-array %this target thisarg argarray))
(define (js-reflect-construct this target argarray newtarget)
(cond
((eq? newtarget (js-undefined))
(apply js-new %this target (js-iterable->list argarray %this)))
((not (js-function? newtarget))
(js-raise-type-error %this "construct: Not an object ~s" newtarget))
((js-function? target)
(with-access::JsFunction target (procedure alloc)
(with-access::JsFunction newtarget (prototype alloc)
(unless prototype
(js-function-setup-prototype! %this newtarget)
(set! alloc js-object-alloc)))
(let* ((o (alloc %this newtarget))
(t (js-apply% %this target procedure o
(js-iterable->list argarray %this)))
(r (if (js-object? t) t o))
(p (js-get newtarget (& "prototype") %this)))
(js-setprototypeof r p %this "construct"))))
(else
(js-raise-type-error %this "construct: Not a function ~s" target))))
(define (js-reflect-defprop this target prop attr)
(let ((name (js-toname prop %this)))
(js-define-own-property target name
(js-to-property-descriptor %this attr name) #f %this)))
(define (js-reflect-delete this target prop attr)
(js-delete! target (js-toname prop %this) #f %this))
(define (js-reflect-get this target prop receiver)
(if (js-object? target)
(if (eq? receiver (js-undefined))
(js-get target prop %this)
(js-get-jsobject target receiver prop %this))
(js-raise-type-error %this "Not an object ~s" target)))
(define (js-reflect-getown this target prop)
(js-get-own-property target (js-toname prop %this) %this))
(define (js-reflect-getproto this target)
(js-getprototypeof target %this "getPrototypeOf"))
(define (js-reflect-hasown this target prop)
(js-has-property target prop %this))
(define (js-reflect-is-extensible this target)
(js-extensible? target %this))
(define (js-reflect-ownkeys this target)
(js-vector->jsarray
(vector-append
(js-properties-name target #f %this)
(js-properties-symbol target %this))
%this))
(define (js-reflect-preventext this target)
(js-preventextensions target %this))
(define (js-reflect-set this target prop v)
(js-put! target prop v #t %this))
(define (js-reflect-setproto this target v)
(with-handler
(lambda (e)
#f)
(begin
(js-setprototypeof target v %this "setPrototypeOf")
#t)))
(js-bind! %this js-reflect (& "apply")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-apply
(js-function-arity js-reflect-apply)
(js-function-info :name "apply" :len 3)))
(js-bind! %this js-reflect (& "construct")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-construct
(js-function-arity js-reflect-construct)
(js-function-info :name "construct" :len 2)))
(js-bind! %this js-reflect (& "defineProperty")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-defprop
(js-function-arity js-reflect-defprop)
(js-function-info :name "defineProperty" :len 3)))
(js-bind! %this js-reflect (& "deleteProperty")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-delete
(js-function-arity js-reflect-delete)
(js-function-info :name "deleteProperty" :len 2)))
(js-bind! %this js-reflect (& "get")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-get
(js-function-arity js-reflect-get)
(js-function-info :name "get" :len 3)))
(js-bind! %this js-reflect (& "getOwnPropertyDescriptor")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-getown
(js-function-arity js-reflect-getown)
(js-function-info :name "getOwnPropertyDescriptor" :len 2)))
(js-bind! %this js-reflect (& "getPrototypeOf")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-getproto
(js-function-arity js-reflect-getproto)
(js-function-info :name "getPrototypeof" :len 1)))
(js-bind! %this js-reflect (& "has")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-hasown
(js-function-arity js-reflect-hasown)
(js-function-info :name "has" :len 2)))
(js-bind! %this js-reflect (& "isExtensible")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-is-extensible
(js-function-arity js-reflect-is-extensible)
(js-function-info :name "isExtensible" :len 1)))
(js-bind! %this js-reflect (& "ownKeys")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-ownkeys
(js-function-arity js-reflect-ownkeys)
(js-function-info :name "ownKeys" :len 1)))
(js-bind! %this js-reflect (& "preventExtensions")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-preventext
(js-function-arity js-reflect-preventext)
(js-function-info :name "preventExtensions" :len 1)))
(js-bind! %this js-reflect (& "set")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-set
(js-function-arity js-reflect-set)
(js-function-info :name "set" :len 3)))
(js-bind! %this js-reflect (& "setPrototypeOf")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-setproto
(js-function-arity js-reflect-setproto)
(js-function-info :name "setPrototypeOf" :len 2)))
;; bind Reflect in the global object
(js-bind! %this %this (& "Reflect")
:configurable #t :enumerable #f :writable #t
:value js-reflect :hidden-class #t)
js-reflect)
;*---------------------------------------------------------------------*/
;* &end! */
;*---------------------------------------------------------------------*/
(&end!)
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/hopscript/reflect.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* Creation : Wed Dec 5 22:00:24 2018 */
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* Reference/Global_Objects/Reflect */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* &begin! */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* js-init-reflect! ... */
*---------------------------------------------------------------------*/
bind Reflect in the global object
*---------------------------------------------------------------------*/
* &end! */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / hop / hop / hopscript / reflect.scm * /
* Author : * /
* Last change : Sun Mar 1 11:17:27 2020 ( serrano ) * /
* Copyright : 2018 - 20 * /
* Native Bigloo support of JavaScript REFLECT object . * /
* -US/docs/Web/JavaScript/ * /
(module __hopscript_reflect
(include "../nodejs/nodejs_debug.sch")
(library hop)
(include "types.sch" "stringliteral.sch")
(import __hopscript_types
__hopscript_arithmetic
__hopscript_lib
__hopscript_object
__hopscript_function
__hopscript_property
__hopscript_private
__hopscript_public
__hopscript_regexp
__hopscript_array
__hopscript_error
__hopscript_worker
__hopscript_spawn)
(export (js-init-reflect! ::JsGlobalObject)))
(define __js_strings (&begin!))
(define (js-init-reflect! %this::JsGlobalObject)
(unless (vector? __js_strings) (set! __js_strings (&init!)))
(define js-reflect
(instantiateJsObject
(__proto__ (js-object-proto %this))
(elements ($create-vector 14))))
(define (js-reflect-apply this target thisarg argarray)
(js-apply-array %this target thisarg argarray))
(define (js-reflect-construct this target argarray newtarget)
(cond
((eq? newtarget (js-undefined))
(apply js-new %this target (js-iterable->list argarray %this)))
((not (js-function? newtarget))
(js-raise-type-error %this "construct: Not an object ~s" newtarget))
((js-function? target)
(with-access::JsFunction target (procedure alloc)
(with-access::JsFunction newtarget (prototype alloc)
(unless prototype
(js-function-setup-prototype! %this newtarget)
(set! alloc js-object-alloc)))
(let* ((o (alloc %this newtarget))
(t (js-apply% %this target procedure o
(js-iterable->list argarray %this)))
(r (if (js-object? t) t o))
(p (js-get newtarget (& "prototype") %this)))
(js-setprototypeof r p %this "construct"))))
(else
(js-raise-type-error %this "construct: Not a function ~s" target))))
(define (js-reflect-defprop this target prop attr)
(let ((name (js-toname prop %this)))
(js-define-own-property target name
(js-to-property-descriptor %this attr name) #f %this)))
(define (js-reflect-delete this target prop attr)
(js-delete! target (js-toname prop %this) #f %this))
(define (js-reflect-get this target prop receiver)
(if (js-object? target)
(if (eq? receiver (js-undefined))
(js-get target prop %this)
(js-get-jsobject target receiver prop %this))
(js-raise-type-error %this "Not an object ~s" target)))
(define (js-reflect-getown this target prop)
(js-get-own-property target (js-toname prop %this) %this))
(define (js-reflect-getproto this target)
(js-getprototypeof target %this "getPrototypeOf"))
(define (js-reflect-hasown this target prop)
(js-has-property target prop %this))
(define (js-reflect-is-extensible this target)
(js-extensible? target %this))
(define (js-reflect-ownkeys this target)
(js-vector->jsarray
(vector-append
(js-properties-name target #f %this)
(js-properties-symbol target %this))
%this))
(define (js-reflect-preventext this target)
(js-preventextensions target %this))
(define (js-reflect-set this target prop v)
(js-put! target prop v #t %this))
(define (js-reflect-setproto this target v)
(with-handler
(lambda (e)
#f)
(begin
(js-setprototypeof target v %this "setPrototypeOf")
#t)))
(js-bind! %this js-reflect (& "apply")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-apply
(js-function-arity js-reflect-apply)
(js-function-info :name "apply" :len 3)))
(js-bind! %this js-reflect (& "construct")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-construct
(js-function-arity js-reflect-construct)
(js-function-info :name "construct" :len 2)))
(js-bind! %this js-reflect (& "defineProperty")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-defprop
(js-function-arity js-reflect-defprop)
(js-function-info :name "defineProperty" :len 3)))
(js-bind! %this js-reflect (& "deleteProperty")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-delete
(js-function-arity js-reflect-delete)
(js-function-info :name "deleteProperty" :len 2)))
(js-bind! %this js-reflect (& "get")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-get
(js-function-arity js-reflect-get)
(js-function-info :name "get" :len 3)))
(js-bind! %this js-reflect (& "getOwnPropertyDescriptor")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-getown
(js-function-arity js-reflect-getown)
(js-function-info :name "getOwnPropertyDescriptor" :len 2)))
(js-bind! %this js-reflect (& "getPrototypeOf")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-getproto
(js-function-arity js-reflect-getproto)
(js-function-info :name "getPrototypeof" :len 1)))
(js-bind! %this js-reflect (& "has")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-hasown
(js-function-arity js-reflect-hasown)
(js-function-info :name "has" :len 2)))
(js-bind! %this js-reflect (& "isExtensible")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-is-extensible
(js-function-arity js-reflect-is-extensible)
(js-function-info :name "isExtensible" :len 1)))
(js-bind! %this js-reflect (& "ownKeys")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-ownkeys
(js-function-arity js-reflect-ownkeys)
(js-function-info :name "ownKeys" :len 1)))
(js-bind! %this js-reflect (& "preventExtensions")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-preventext
(js-function-arity js-reflect-preventext)
(js-function-info :name "preventExtensions" :len 1)))
(js-bind! %this js-reflect (& "set")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-set
(js-function-arity js-reflect-set)
(js-function-info :name "set" :len 3)))
(js-bind! %this js-reflect (& "setPrototypeOf")
:configurable #t :enumerable #f :writable #t
:value (js-make-function %this js-reflect-setproto
(js-function-arity js-reflect-setproto)
(js-function-info :name "setPrototypeOf" :len 2)))
(js-bind! %this %this (& "Reflect")
:configurable #t :enumerable #f :writable #t
:value js-reflect :hidden-class #t)
js-reflect)
(&end!)
|
8b01a43ba1f9895ec943dab52e1b7beda49dd125ab9c1e2b6154d412845356e9 | albertoruiz/easyVision | roiclass.hs | -- detection of rois based on examples labeled by roisel
$ ./roiclass ' newvideo -benchmark ' test etc .
import EasyVision
import Graphics.UI.GLUT hiding (histogram)
import Control.Monad(when)
import System.Environment(getArgs)
import Numeric.LinearAlgebra
import Classifier
import Data.List(maximumBy)
import Util.Misc(vec)
import Util.Probability(evidence)
import Util
genrois = roiGridStep 50 200 25 25
commonproc = highPass8u Mask5x5 . median Mask5x5 . grayscale . channels
feat = vec . map fromIntegral . histogram [0,8 .. 256]
machine = multiclass mse
main = do
sz <- findSize
video:test:files <- getArgs
prepare
rawexamples <- mapM (readSelectedRois sz) files
let examples = concatMap (createExamples commonproc genrois feat) (concat rawexamples)
classifier = machine examples
putStrLn $ show (length examples) ++ " total examples"
rawtest <- readSelectedRois sz test
let test = concatMap (createExamples commonproc genrois feat) rawtest
putStrLn $ show (length test) ++ " total test examples"
-- shQuality test classifier
shConf test (Just . mode . classifier)
shErr test (Just . mode . classifier)
(camtest,ctrl) <- mplayer video sz >>= detectStatic 0.01 5 5 (grayscale.channels) id >>= withPause
w <- evWindow () "Plates detection" sz Nothing (const (kbdcam ctrl))
launch $ inWin w $ do
img <- camtest
drawImage img
let imgproc = commonproc img
candis = map (\r -> (r,imgproc)) (genrois (theROI img))
lineWidth $= 1
setColor' gray
let pos = filter ((=="+"). mode . classifier. overROI feat) candis
mapM_ (drawROI.fst) pos
when (not.null $ pos) $ do
lineWidth $= 3
setColor' red
let best = maximumBy (compare `on` (evidence "+" . classifier) . overROI feat) pos
drawROI (fst best)
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/old/tutorial/roiclass.hs | haskell | detection of rois based on examples labeled by roisel
shQuality test classifier | $ ./roiclass ' newvideo -benchmark ' test etc .
import EasyVision
import Graphics.UI.GLUT hiding (histogram)
import Control.Monad(when)
import System.Environment(getArgs)
import Numeric.LinearAlgebra
import Classifier
import Data.List(maximumBy)
import Util.Misc(vec)
import Util.Probability(evidence)
import Util
genrois = roiGridStep 50 200 25 25
commonproc = highPass8u Mask5x5 . median Mask5x5 . grayscale . channels
feat = vec . map fromIntegral . histogram [0,8 .. 256]
machine = multiclass mse
main = do
sz <- findSize
video:test:files <- getArgs
prepare
rawexamples <- mapM (readSelectedRois sz) files
let examples = concatMap (createExamples commonproc genrois feat) (concat rawexamples)
classifier = machine examples
putStrLn $ show (length examples) ++ " total examples"
rawtest <- readSelectedRois sz test
let test = concatMap (createExamples commonproc genrois feat) rawtest
putStrLn $ show (length test) ++ " total test examples"
shConf test (Just . mode . classifier)
shErr test (Just . mode . classifier)
(camtest,ctrl) <- mplayer video sz >>= detectStatic 0.01 5 5 (grayscale.channels) id >>= withPause
w <- evWindow () "Plates detection" sz Nothing (const (kbdcam ctrl))
launch $ inWin w $ do
img <- camtest
drawImage img
let imgproc = commonproc img
candis = map (\r -> (r,imgproc)) (genrois (theROI img))
lineWidth $= 1
setColor' gray
let pos = filter ((=="+"). mode . classifier. overROI feat) candis
mapM_ (drawROI.fst) pos
when (not.null $ pos) $ do
lineWidth $= 3
setColor' red
let best = maximumBy (compare `on` (evidence "+" . classifier) . overROI feat) pos
drawROI (fst best)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.