lattest-lib-0.2: src/Lattest/Util/STSJSONParser.hs
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
module Lattest.Util.STSJSONParser (
stsFromJSONFile,
stsListFromJSONFile,
) where
import Control.Monad (forM)
import Data.Foldable (toList)
import qualified Data.Aeson as JSON
import Data.Dependent.Sum (DSum (..))
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as Map
import Data.Scientific (toRealFloat)
import qualified Data.Set as Set
import Data.Text (unpack)
import Data.Maybe (fromMaybe)
import Lattest.Model.Alphabet (IOAct (..), SymInteract (..))
import Lattest.Model.Automaton (stsTLoc, STStdest)
import Lattest.Model.BoundedMonad (FreeLattice, atom, (/\))
import Lattest.Model.StandardAutomata (IOSTS, automaton)
import Lattest.Model.Symbolic.Expr
import Data.Some (Some (..))
import Data.Type.Equality ((:~:)(..))
import Data.GADT.Compare (GEq(..))
import Lattest.Model.Symbolic.Internal.ExprDefs (Expr (..))
import Data.SBV (AlgReal)
import qualified Data.Aeson.Types as JSON
import qualified Data.Aeson.KeyMap as JSON
import Data.Aeson.Key (toString)
import qualified Debug.Trace
-- enum plan:
-- like 'type: "structure"' implying 'attributes', 'type: "enum"' will imply 'range'.
data UntypedExpr
= UEBool Bool
| UEFloat Double
| UERational Rational
| UEReal AlgReal
| UEInt Integer
| UEStr String
| UEVar String -- Variable reference, e.g. { "var": "name" }
| UEEnum String -- Enum constructor
| UEOp1 String UntypedExpr
| UEOp2 String UntypedExpr UntypedExpr
-- Op3 and Op5 always start with one or two variable names { "lambda": "name" }, respectively
| UEOp3 String String UntypedExpr UntypedExpr
| UEOp5 String String String UntypedExpr UntypedExpr UntypedExpr
deriving (Show, Eq)
data HideArgumentOfFunction = forall a. JSON.FromJSON a => X (a -> UntypedExpr) -- only used in the instance below
instance JSON.FromJSON UntypedExpr where
parseJSON (JSON.Bool b) = pure (UEBool b)
parseJSON (JSON.Number _) = error "untagged constant integer or float"
parseJSON (JSON.String s) = pure (UEStr (unpack s))
parseJSON (JSON.Object o) = do
foldr
(\(field, X constructor) rec -> do
m <- o JSON..:? field
case m of
Just x -> pure $ constructor x
Nothing -> rec)
(do
(op :: String) <- o JSON..: "op"
case op of
"neg" -> UEOp1 op <$> o JSON..: "rhs"
"not" -> UEOp1 op <$> o JSON..: "rhs"
"len" -> UEOp1 op <$> o JSON..: "rhs"
"head" -> UEOp1 op <$> o JSON..: "rhs"
"tail" -> UEOp1 op <$> o JSON..: "rhs"
"concat" -> UEOp1 op <$> o JSON..: "rhs"
"uniqueElem" -> UEOp1 op <$> o JSON..: "rhs"
"first" -> UEOp1 op <$> o JSON..: "rhs"
"second" -> UEOp1 op <$> o JSON..: "rhs"
"map" -> UEOp3 op <$> o JSON..: "lambda" <*> o JSON..: "fun" <*> o JSON..: "lst"
"filter" -> UEOp3 op <$> o JSON..: "lambda" <*> o JSON..: "fun" <*> o JSON..: "lst"
"forall" -> UEOp3 op <$> o JSON..: "lambda" <*> o JSON..: "expression" <*> o JSON..: "over"
"exists" -> UEOp3 op <$> o JSON..: "lambda" <*> o JSON..: "expression" <*> o JSON..: "over"
"cardinality" -> UEOp5 op <$> o JSON..: "lambda" <*> o JSON..: "quantifier" <*> o JSON..: "expression" <*> o JSON..: "over" <*> (UEInt <$> o JSON..: "n")
"foldr" -> UEOp5 op <$> o JSON..: "lama" <*> o JSON..: "lamb" <*> o JSON..: "func" <*> o JSON..: "init" <*> o JSON..: "list"
"foldl" -> UEOp5 op <$> o JSON..: "lamb" <*> o JSON..: "lama" <*> o JSON..: "func" <*> o JSON..: "init" <*> o JSON..: "list"
"either" -> UEOp5 op <$> o JSON..: "lama" <*> o JSON..: "lamb" <*> o JSON..: "funa" <*> o JSON..: "funb" <*> o JSON..: "eith"
_ -> UEOp2 op <$> o JSON..: "lhs" <*> o JSON..: "rhs"
)
[ ("var", X UEVar)
, ("integer", X UEInt)
, ("float", X UEFloat)
, ("rational", X UERational)
, ("real", X UEReal)
, ("boolean", X UEBool)
, ("string", X UEStr)
, ("enum", X UEEnum)
]
parseJSON _ = fail "expected expression"
type VarMap = Map.Map String (Some Variable)
type AccessorMap = Map.Map String FieldAccessor
type EnumMap = Map.Map String (Some Expr)
type AttrNameMap = Map.Map (Some Type, [Bool]) String
lookupVar :: VarMap -> String -> Either String (DSum Type Expr)
lookupVar varmap name = case Map.lookup name varmap of
Just (Some v@(Variable _ t)) -> Right $ t :=> sVar v
Nothing -> Left $ "unknown variable: " ++ name
lookupEnum :: EnumMap -> String -> Either String (DSum Type Expr)
lookupEnum m nm = case m Map.!? nm of
Just (Some e) -> withExprConstraints e $ Right $ typeOf' e :=> e
Nothing -> Left $ "unknown enum constructor: " <> nm
data TwoExprs a = Two (Expr a) (Expr a)
toExpr :: VarMap -> AccessorMap -> EnumMap -> UntypedExpr -> Either String (DSum Type Expr)
toExpr varmap accmap enummap = \case
UEVar name -> lookupVar varmap name
UEEnum name -> lookupEnum enummap name
UEBool b -> Right $ BoolType :=> sConst b
UEInt i -> Right $ IntType :=> sConst i
UEFloat f -> Right $ FloatType :=> sConst f
UERational f -> Right $ RationalType :=> sConst f
UEReal f -> Right $ RealType :=> sConst f
UEStr s -> Right $ ListType CharType :=> sConst s
UEOp1 o e -> go e >>= op1 o
UEOp2 "project" e (UEVar f) -> -- need to handle this here, because for all other Op2's we check the types (and field accessors do not have a type here)
case accmap Map.!? f of
Just (FA tbig tsmall g) -> do
t :=> e' <- go e
case geq tbig t of
Nothing -> error $ "mismatched input type to field accessor " <> f <> ": " <> show t <> " , expected " <> show tbig
Just Refl -> case g e' of
e'' -> Right $ tsmall :=> e''
Nothing -> Left $ "unknown field projection: " <> f
UEOp2 o e1 e2 -> do
t1 :=> x <- go e1
t2 :=> y <- go e2
case geq t1 t2 of
Just Refl -> op2ET o (t1 :=> Two x y)
Nothing -> op2 o (t1 :=> x) (t2 :=> y)
UEOp3 o v e1 e2 -> op3 o v e1 e2
UEOp5 o v1 v2 e1 e2 e3 -> op5 o v1 v2 e1 e2 e3
where
-- ExprViews that don't (yet) have a parse:
-- Ite
go = toExpr varmap accmap enummap
op1 :: String -> DSum Type Expr -> Either String (DSum Type Expr)
op1 o (tp :=> x) = case tp of
BoolType -> case o of
"not" -> Right $ BoolType :=> sNot x
_ -> Left $ "unknown op1 @Bool: " <> o
IntType -> case o of
"neg" -> Right $ IntType :=> sNeg x
_ -> Left $ "unknown op1 @Int: " <> o
FloatType -> case o of
"neg" -> Right $ FloatType :=> sNeg x
_ -> Left $ "unknown op1 @Float: " <> o
RationalType -> case o of
"neg" -> Right $ RationalType :=> sNeg x
_ -> Left $ "unknown op1 @Rational: " <> o
RealType -> case o of
"neg" -> Right $ RealType :=> sNeg x
_ -> Left $ "unknown op1 @Real: " <> o
ListType t -> withExprConstraints t case o of
"concat" -> case t of
ListType t' -> withExprConstraints t' $ Right $ t :=> sConcat x
_ -> Left "concat on non-nested list"
"len" -> Right $ IntType :=> sLength x
"head" -> Right $ t :=> sHead x
"tail" -> Right $ ListType t :=> sTail x
"uniqueElem" -> Right $ BoolType :=> let seen = Variable "uniqueSeen" (TupleType BoolType $ ListType t)
y = Variable "uniqueIterator" t
step = sIfThenElse
(sFirst (sVar seen) .&& sNot (sElem (sVar y) (sSecond $ sVar seen)))
(sPair sTrue $ sCons (sVar y) (sSecond $ sVar seen))
(sFalse `sPair` sSecond (sVar seen)) -- even though the list is irrelevant here, z3 is much faster at consuming this version than with sNil here. I guess it recognizes a pattern? I don't see a difference in speed between consing y or not.
in sFirst $ sFoldr y seen step (sPair sTrue sNil) x
_ -> Left $ "unknown op1 @List: " <> o
TupleType t1 t2 -> withExprConstraints t1 $ withExprConstraints t2 case o of
"first" -> Right $ t1 :=> sFirst x
"second" -> Right $ t2 :=> sSecond x
_ -> Left $ "unknown op1 @Tuple: " <> o
_ -> error "unkown op1"
-- for two equally-typed expressions
op2ET :: String -> DSum Type TwoExprs -> Either String (DSum Type Expr)
op2ET "==" (t :=> Two x y) = withExprConstraints t $ Right $ BoolType :=> x .== y
op2ET "!=" (t :=> Two x y) = withExprConstraints t $ Right $ BoolType :=> sNot (x .== y)
op2ET o (t :=> Two x y) = case t of
BoolType -> case o of
"&&" -> Right $ BoolType :=> x .&& y
"||" -> Right $ BoolType :=> x .|| y
_ -> op2 o (t :=> x) (t :=> y)
IntType -> case o of
"%" -> Right $ t :=> x .% y
"/" -> Right $ t :=> x ./ y
"+" -> Right $ t :=> x .+ y
"-" -> Right $ t :=> x .- y
"*" -> Right $ t :=> x .* y
"<" -> Right $ BoolType :=> x .< y
"<=" -> Right $ BoolType :=> x .<= y
">" -> Right $ BoolType :=> x .> y
">=" -> Right $ BoolType :=> x .>= y
_ -> op2 o (t :=> x) (t :=> y)
FloatType -> case o of
"/" -> Right $ t :=> x ./ y
"+" -> Right $ t :=> x .+ y
"-" -> Right $ t :=> x .- y
"*" -> Right $ t :=> x .* y
"<" -> Right $ BoolType :=> x .< y
"<=" -> Right $ BoolType :=> x .<= y
">" -> Right $ BoolType :=> x .> y
">=" -> Right $ BoolType :=> x .>= y
_ -> op2 o (t :=> x) (t :=> y)
RationalType -> case o of
"/" -> Right $ t :=> x ./ y
"+" -> Right $ t :=> x .+ y
"-" -> Right $ t :=> x .- y
"*" -> Right $ t :=> x .* y
"<" -> Right $ BoolType :=> x .< y
"<=" -> Right $ BoolType :=> x .<= y
">" -> Right $ BoolType :=> x .> y
">=" -> Right $ BoolType :=> x .>= y
_ -> op2 o (t :=> x) (t :=> y)
RealType -> case o of
"/" -> Right $ t :=> x ./ y
"+" -> Right $ t :=> x .+ y
"-" -> Right $ t :=> x .- y
"*" -> Right $ t :=> x .* y
"<" -> Right $ BoolType :=> x .< y
"<=" -> Right $ BoolType :=> x .<= y
">" -> Right $ BoolType :=> x .> y
">=" -> Right $ BoolType :=> x .>= y
_ -> op2 o (t :=> x) (t :=> y)
ListType _ -> case o of
"++" -> Right $ t :=> sAppend x y
_ -> op2 o (t :=> x) (t :=> y)
_ -> op2 o (t :=> x) (t :=> y)
-- for two potentially unequally-typed expressions
op2 :: String -> DSum Type Expr -> DSum Type Expr -> Either String (DSum Type Expr)
op2 "cons" (t1 :=> x) (ListType t2 :=> xs) = case geq t1 t2 of
Just Refl -> Right $ ListType t1 :=> sCons x xs
Nothing -> Left "mismatched type for cons"
op2 "elem" (t1 :=> x) (ListType t2 :=> xs) = case geq t1 t2 of
Just Refl -> Right $ BoolType :=> sElem x xs
Nothing -> Left "mismatched type for list elem"
op2 "take" (IntType :=> i) (ListType t :=> xs) = Right $ ListType t :=> sTake i xs
op2 "drop" (IntType :=> i) (ListType t :=> xs) = Right $ ListType t :=> sDrop i xs
op2 "pair" (t1 :=> x) (t2 :=> y) = Right $ TupleType t1 t2 :=> sPair x y
op2 o _ _ = Left $ "unknown or badly typed op2: " <> o
op3 :: String -> String -> UntypedExpr -> UntypedExpr -> Either String (DSum Type Expr)
op3 op v f xs = do
t'' :=> ys <- go xs
case t'' of
ListType t -> do
t' :=> g <- toExpr (Map.insert v (Some (Variable v t)) varmap) accmap enummap f
withExprConstraints t $ withExprConstraints t' case op of
"map" -> Right $ ListType t' :=> sMap (Variable v t) g ys
"filter" -> case geq BoolType t' of
Just Refl -> Right $ ListType t :=> sFilter (Variable v t) g ys
Nothing -> Left "non-bool function in filter"
"forall" -> case geq BoolType t' of
Just Refl -> Right $ BoolType :=> let y = Variable "forallAccumulator" BoolType
x = Variable "forallIterator" BoolType
in sFoldr x y (sVar x .&& sVar y) sTrue $ sMap (Variable v t) g ys
Nothing -> Left "non-bool function in forall"
"exists" -> case geq BoolType t' of
Just Refl -> Right $ BoolType :=> let y = Variable "existsAccumulator" BoolType
x = Variable "existsIterator" BoolType
in sFoldr x y (sVar x .|| sVar y) sFalse $ sMap (Variable v t) g ys
Nothing -> Left "non-bool function in forall"
_ -> Left $ "unknown or mistyped op3: " <> op
_ -> Left "op3 received non-list as third expression"
op5 :: String -> String -> String -> UntypedExpr -> UntypedExpr -> UntypedExpr -> Either String (DSum Type Expr)
op5 "either" v1 v2 e1 e2 e3 = do
st :=> e <- go e3
case st of
SumType t1 t2 -> do
t :=> l <- toExpr (Map.insert v1 (Some (Variable v1 t1)) varmap) accmap enummap e1
t' :=> r <- toExpr (Map.insert v2 (Some (Variable v2 t2)) varmap) accmap enummap e2
withExprConstraints t1 $ withExprConstraints t2 $ withExprConstraints t case geq t t' of
Just Refl -> Right $ t :=> sEither (Variable v1 t1) (Variable v2 t2) l r e
Nothing -> Left "wrongly typed either"
_ -> Left "non-Either in either"
op5 "foldr" v1 v2 f i xs = do
lt :=> ys <- go xs
case lt of
ListType ta -> do
tb :=> i' <- go i
tb' :=> g <- toExpr (Map.insert v1 (Some (Variable v1 ta)) $ Map.insert v2 (Some (Variable v2 tb)) varmap) accmap enummap f
withExprConstraints ta case geq tb tb' of
Just Refl -> Right $ tb :=> sFoldr (Variable v1 ta) (Variable v2 tb) g i' ys
Nothing -> Left "wrongly typed foldr"
_ -> Left "non-list in foldr"
op5 "foldl" v1 v2 f i xs = do
lt :=> ys <- go xs
case lt of
ListType ta -> do
tb :=> i' <- go i
tb' :=> g <- toExpr (Map.insert v1 (Some (Variable v1 tb)) $ Map.insert v2 (Some (Variable v2 ta)) varmap) accmap enummap f
withExprConstraints ta case geq tb tb' of
Just Refl -> Right $ tb :=> sFoldl (Variable v1 tb) (Variable v2 ta) g i' ys
Nothing -> Left "wrongly typed foldr"
_ -> Left "non-list in foldl"
-- "cardinality" is the only case that doesn't actually take 2 variables and 3 expressions;
-- we just pass the 'quantity' string in place of the second variable and the size as the final UE
op5 "cardinality" v quantity f xs (UEInt n) =
op3 "filter" v f xs >>= \case
ListType _ :=> ys -> case quantity of
"exactly" -> Right $ BoolType :=> sLength ys .== sConst n
"at_least" -> Right $ BoolType :=> sLength ys .>= sConst n
"at_most" -> Right $ BoolType :=> sLength ys .<= sConst n
_ -> Left "unknown quantifier in cardinality"
_ -> error "op3 'filter' did something very weird"
op5 _ _ _ _ _ _ = Left "unkown or wrongly typed op5"
-- Location IDs can be integers or strings in JSON; both are mapped to String for consistency.
newtype LocationId = LocationId { locId :: String }
instance JSON.FromJSON LocationId where
parseJSON v = case v of
JSON.String s -> pure $ LocationId (unpack s)
JSON.Number n -> pure $ LocationId (show (round n :: Integer))
_ -> fail $ "expected string or number for LocationId, got: " ++ show v
newtype GateId = GateId { unGateId :: String }
-- Gate IDs can be integers or strings in JSON; both are mapped to String for consistency.
instance JSON.FromJSON GateId where
parseJSON v = case v of
JSON.String s -> pure $ GateId (unpack s)
JSON.Number n -> pure $ GateId (show (round n :: Integer))
_ -> fail $ "expected string or number for GateId, got: " ++ show v
-- type, and a list of field accessors
data VarDefJson = VarDefJson { varDefJsonType :: Some Type
, varDefJsonFieldAccessors :: Map.Map String FieldAccessor
, varDefJsonEnumDefs :: EnumMap
, varDefJsonAttrNames :: AttrNameMap}
newtype MkEnumResult tp = MER (Map.Map String (Expr tp))
data FieldAccessor where
FA :: Type big -> Type small -> (Expr big -> Expr small) -> FieldAccessor
instance JSON.FromJSON VarDefJson where
parseJSON = JSON.withObject "VarDefJson" go
where
go :: JSON.Object -> JSON.Parser VarDefJson
go o = do
tp :: String <- o JSON..: "type"
case tp of
"int" -> k $ Some IntType
"integer" -> k $ Some IntType
"bool" -> k $ Some BoolType
"boolean" -> k $ Some BoolType
"string" -> k $ Some $ ListType CharType
"char" -> k $ Some CharType
"()" -> k $ Some UnitType
"float" -> k $ Some FloatType
"rational"-> k $ Some RationalType
"real" -> k $ Some RealType
"array" -> do
o' <- o JSON..: "elements"
VarDefJson (Some t) a b n <- go o'
pure $ VarDefJson (Some $ ListType t) a b n
"structure" -> do
JSON.Object o' <- o JSON..: "attributes"
((t, a), (b,c,n)) <- mkStructure $ JSON.toList o'
pure $ VarDefJson t (a <> b) c (unionAttrNames (fieldNames a) n)
"enum" -> do
range <- o JSON..: "range"
case mkEnum range of
t :=> MER m -> pure $ VarDefJson (Some t) mempty (Map.map Some m) mempty
_ -> fail $ "unknown variable type: " ++ tp
k tp = pure $ VarDefJson tp mempty mempty mempty
mkEnum :: [String] -> DSum Type MkEnumResult
mkEnum [] = error "empty enum"
mkEnum [nm] = UnitType :=> MER (Map.singleton nm $ Expr $ Const ())
mkEnum (nm:rest) = case mkEnum rest of
tp :=> MER m -> withExprConstraints tp $
SumType UnitType tp :=> MER (Map.insertWith
(error "option present twice in one range")
nm
(Expr $ ELeft $ Const ())
(Map.map sRight m))
mkStructure [] = error "empty structure"
mkStructure [(nm, JSON.Object o)] = do
VarDefJson (Some tp) a b n <- go o
pure ((Some tp, Map.singleton (toString nm) (FA tp tp id)), (a,b,n))
mkStructure ((nm, JSON.Object o) : fields) = do
VarDefJson (Some (ta :: Type a)) a x n <- go o
((Some (tb :: Type b), accessors), (b,y,m)) <- mkStructure fields
withExprConstraints ta $ withExprConstraints tb $
pure
( (Some (TupleType ta tb)
, Map.insertWith
errIfUnequalAccessors
(toString nm)
(FA (TupleType ta tb) ta sFirst)
(Map.map (\(FA tbig tsmall f) -> case geq tbig tb of
Nothing -> error "unexpected result type in mkStructure: this is the result of a call on the tail of the same list"
Just Refl ->FA (TupleType ta tb) tsmall (f . sSecond)) accessors))
, (Map.unionWith errIfUnequalAccessors a b, Map.unionWith errIfUnequalEnums x y, unionAttrNames n m))
mkStructure _ = error "non-object in attributes"
-- | The names of the attributes of a structure
fieldNames :: Map.Map String FieldAccessor -> AttrNameMap
fieldNames accessors = Map.fromList
[ ((Some t, path), nm)
| (nm, FA t _ f) <- Map.toList accessors
, e <- [f $ Expr $ Var $ Variable "" t]
, let path = projections (view e)
, not (null path) -- a structure with a single attr is that attr
]
where
projections :: ExprView a -> [Bool]
projections (First _ x) = projections x ++ [False]
projections (Second _ x) = projections x ++ [True]
projections _ = []
-- | Two structures of the same type have their attrs in the same places, such a place gets both names.
unionAttrNames :: AttrNameMap -> AttrNameMap -> AttrNameMap
unionAttrNames = Map.unionWith (\a b -> if a == b then a else a <> "/" <> b)
errIfUnequalAccessors :: FieldAccessor -> FieldAccessor -> FieldAccessor
errIfUnequalAccessors x@(FA tbig1 tsmall1 f1) (FA tbig2 tsmall2 f2) = case geq tbig1 tbig2 of
Nothing -> error "different expected types for the same field accessor"
Just Refl -> case geq tsmall1 tsmall2 of
Nothing -> error "different resulting types for the same field accessor"
Just Refl -> let v = Variable "foo" tbig1 in if f1 (sVar v) == f2 (sVar v) then x else error "different functions for the same field accessor"
errIfUnequalEnums :: Some Expr -> Some Expr -> Some Expr
errIfUnequalEnums (Some a) (Some b) = withExprConstraints a $ withExprConstraints b $ case geq (typeOf' a) (typeOf' b) of
Nothing -> error "different types for the same enum constructor"
Just Refl -> if a == b then Some a else error "different constructors for the same enum name"
data GateDefJson = GateDefJson
{ gateDefJsonShortname :: Maybe String
, gateDefJsonParams :: [String]
}
instance JSON.FromJSON GateDefJson where
parseJSON = JSON.withObject "GateDefJson" $ \o ->
GateDefJson <$> o JSON..:? "shortname"
<*> o JSON..: "parameters"
data AssignmentDefJson = AssignmentDefJson
{ assignmentJsonVar :: String
, assignmentJsonExpr :: UntypedExpr
}
instance JSON.FromJSON AssignmentDefJson where
parseJSON = JSON.withObject "AssignmentDefJson" $ \o ->
AssignmentDefJson <$> o JSON..: "target" <*> o JSON..: "expression"
data SwitchDefJson = SwitchDefJson
{ switchJsonInitLoc :: LocationId
, switchJsonGate :: GateId
, switchJsonGuard :: Maybe [String] -- names of guards to be conjoined
, switchJsonAssignments :: [String]
, switchJsonEndLoc :: LocationId
}
-- A "guard" field may be a single guard name, or an array of guard names (merged with &&).
instance JSON.FromJSON SwitchDefJson where
parseJSON = JSON.withObject "SwitchDefJson" $ \o ->
SwitchDefJson
<$> o JSON..: "init_loc"
<*> o JSON..: "gate"
<*> (o JSON..:? "guard" >>= traverse parseGuardNames)
<*> (o JSON..:? "assignments" JSON..!= [])
<*> o JSON..: "end_loc"
where
parseGuardNames (JSON.String s) = pure [unpack s]
parseGuardNames (JSON.Array a) = mapM parseGuardName (toList a)
parseGuardNames _ = fail "guard must be a string or an array of strings"
parseGuardName (JSON.String s) = pure (unpack s)
parseGuardName _ = fail "guard array elements must be strings"
data STSJsonFormat = STSJsonFormat
{ stsJsonId :: String
, stsJsonInitLoc :: LocationId
, stsJsonLocVars :: Map.Map String VarDefJson
, stsJsonParams :: Map.Map String VarDefJson
, stsJsonInitValuation :: Map.Map String JSON.Value
, stsJsonLocations :: [LocationId]
, stsJsonInputGates :: Map.Map String GateDefJson
, stsJsonOutputGates :: Map.Map String GateDefJson
, stsJsonGuards :: Map.Map String UntypedExpr
, stsJsonAssignments :: Map.Map String AssignmentDefJson
, stsJsonSwitches :: Map.Map String SwitchDefJson
}
instance JSON.FromJSON STSJsonFormat where
parseJSON = JSON.withObject "STSJsonFormat" $ \o ->
STSJsonFormat
<$> (o JSON..:? "id" JSON..!= "")
<*> o JSON..: "initial_location"
<*> o JSON..: "locationVariables"
<*> o JSON..: "parameters"
<*> (o JSON..:? "initialValuation" JSON..!= Map.empty)
<*> o JSON..: "locations"
<*> o JSON..: "inputGates"
<*> o JSON..: "outputGates"
<*> o JSON..: "guards"
<*> (o JSON..:? "assignments" JSON..!= Map.empty)
<*> o JSON..: "switches"
-- STS elements builders
buildVarMap :: Map.Map String VarDefJson -> Either String (VarMap, AccessorMap, EnumMap, AttrNameMap)
buildVarMap defs = do
(varmap, unzip3 -> (accessorss, enumss, fieldss)) <- unzip <$> forM (Map.toList defs)
(\(name, VarDefJson (Some t') accessors enums fields) -> return ((name, Some $ Variable name t'), (accessors, enums, fields)))
let accessors = Map.unionsWith errIfUnequalAccessors accessorss
let enums = Map.unionsWith errIfUnequalEnums enumss
let varmap' = Map.fromList varmap
pure (varmap', accessors, enums, foldr unionAttrNames mempty fieldss)
buildGateMap
:: (String -> IOAct String String)
-> VarMap
-> Map.Map String GateDefJson
-> Either String (Map.Map String (SymInteract (IOAct String String)))
buildGateMap mkGate varMap defs = Map.fromList <$> forM (Map.toList defs) (\(name, def) -> do
let gateName = fromMaybe name (gateDefJsonShortname def)
params <- forM (gateDefJsonParams def) $ \pname ->
case Map.lookup pname varMap of
Just v -> Right v
Nothing -> Left $ "unknown parameter '" ++ pname ++ "' in gate '" ++ name ++ "'"
return (name, SymInteract (mkGate gateName) params))
buildAssignment
:: VarMap
-> AccessorMap
-> EnumMap
-> String
-> AssignmentDefJson
-> Either String (VarModel -> VarModel)
buildAssignment varMap accmap enummap name def = do
var <- case Map.lookup (assignmentJsonVar def) varMap of
Just v -> Right v
Nothing -> Left $ "unknown variable '" ++ assignmentJsonVar def ++ "' in assignment '" ++ name ++ "'"
let expr = assignmentJsonExpr def
case var of
Some v -> toExpr varMap accmap enummap expr >>= \(tp :=> e) ->
case geq (varType v) tp of
Just Refl -> Right $ v =: e
Nothing -> Left "assigment to variable of wrong type"
buildAssignmentMap
:: VarMap
-> AccessorMap
-> EnumMap
-> Map.Map String AssignmentDefJson
-> Either String (Map.Map String (VarModel -> VarModel))
buildAssignmentMap varMap accMap enummap defs =
Map.fromList <$> forM (Map.toList defs) (\(name, def) ->
(name,) <$> buildAssignment varMap accMap enummap name def)
buildVarModel
:: Map.Map String (VarModel -> VarModel)
-> [String]
-> String
-> Either String VarModel
buildVarModel assignMap names switchName = do
updates <- forM names $ \aname ->
case Map.lookup aname assignMap of
Just f -> Right f
Nothing -> Left $ "unknown assignment '" ++ aname ++ "' in switch '" ++ switchName ++ "'"
return (assignment updates)
buildSwitchList
:: Map.Map String (SymInteract (IOAct String String))
-> Map.Map String (Expr Bool)
-> Map.Map String (VarModel -> VarModel)
-> Map.Map String SwitchDefJson
-> Either String [(String, SymInteract (IOAct String String), Expr Bool, VarModel, String)]
buildSwitchList gateMap guardMap assignMap switchDefs =
forM (Map.toList switchDefs) $ \(name, def) -> do
gate <- case Map.lookup (unGateId (switchJsonGate def)) gateMap of
Just a -> Right a
Nothing -> Left $ "unknown gate '" ++ unGateId (switchJsonGate def) ++ "' in switch '" ++ name ++ "'"
guard' <- case switchJsonGuard def of
Nothing -> Right sTrue
Just gnames -> foldr (.&&) sTrue <$> forM gnames (\gname -> case Map.lookup gname guardMap of
Just g -> Right g
Nothing -> Left $ "unknown guard '" ++ gname ++ "' in switch '" ++ name ++ "'")
varModel <- buildVarModel assignMap (switchJsonAssignments def) name
let initLoc = locId (switchJsonInitLoc def)
endLoc = locId (switchJsonEndLoc def)
return (initLoc, gate, guard', varModel, endLoc)
-- NOTE: transitions from the same location with matching gates are combined with /\
buildTransitionRel
:: [(String, SymInteract (IOAct String String), Expr Bool, VarModel, String)]
-> String
-> Map.Map (SymInteract (IOAct String String)) (FreeLattice (STStdest, String))
buildTransitionRel switchList loc =
Map.fromListWith (/\)
[ (gate, atom (stsTLoc guard' varModel, endLoc))
| (initLoc, gate, guard', varModel, endLoc) <- switchList
, initLoc == loc
]
buildValuation :: Map.Map String (Some Variable) -> Map.Map String JSON.Value -> EnumMap -> Either String Valuation
buildValuation locVarCtx initVal enums =
fmap (assignValues . map snd) $ forM (Map.toList locVarCtx) $ \(name, Some var) ->
case Map.lookup name initVal of
Just v -> case jsonToValue (varType var) v of
Just x -> Right (name, insertIntoValuation var (withExprConstraints var $ Constant x))
Nothing -> Left $ "wrong type for initial value of '" ++ name ++ "', expected " ++ show (varType var)
Nothing -> Debug.Trace.trace ("Missing initial valuation for " <> name <> ", assuming default: " <> withExprConstraints (varType var) show (defaultConst (varType var))) $ Right (name, insertIntoValuation var (defaultConst (varType var)))
where
-- arrays are given as JSON arrays of their elements
jsonToValue :: Type t -> JSON.Value -> Maybe t
jsonToValue IntType (JSON.Number n) = Just (round n)
jsonToValue BoolType (JSON.Bool b) = Just b
jsonToValue CharType (JSON.String (unpack -> [c])) = Just c
jsonToValue FloatType (JSON.Number n) = Just (toRealFloat n)
jsonToValue RationalType (JSON.Number n) = Just (toRational n)
jsonToValue RealType (JSON.Number n) = Just (fromRational $ toRational n)
jsonToValue (ListType CharType) (JSON.String s) = Just (unpack s)
jsonToValue (ListType t) (JSON.Array a) = mapM (jsonToValue t) (toList a)
jsonToValue t (JSON.String s) = case enums Map.!? unpack s of
Just (Some e) -> withExprConstraints e $ case geq t (typeOf' e) of
Just Refl -> case eval e of
Left str -> error $ "Evaluating the enum field failed: " <> str
Right x -> Just x
Nothing -> Nothing
Nothing -> Nothing
jsonToValue _ _ = Nothing
defaultConst :: Type t -> Constant t
defaultConst IntType = Constant 0
defaultConst UnitType = Constant ()
defaultConst FloatType = Constant 0.0
defaultConst RationalType = Constant 0.0
defaultConst RealType = Constant 0.0
defaultConst BoolType = Constant False
defaultConst CharType = Constant 'a'
defaultConst (ListType t) = withExprConstraints t $ Constant []
defaultConst t@(TupleType a b) = withExprConstraints t $ Constant (constValue $ defaultConst a, constValue $ defaultConst b)
defaultConst t@(SumType a _) = withExprConstraints t $ Constant (Left $ constValue $ defaultConst a)
-- | The IOSTS is the main result, but parsing also returns the ID, maps containing the guards and assignments for printing, the initial valuation,
-- the enums, and the names of the fields of the structures for printing.
type STSParseResult = (String, IOSTS FreeLattice String String String, Map.Map String (Expr Bool), Map.Map String VarModel, Valuation, EnumMap, AttrNameMap)
convertSTSJson :: STSJsonFormat -> Either String STSParseResult
convertSTSJson json = do
(locVarMap, accessors1, enums1, fields1) <- buildVarMap (stsJsonLocVars json)
(paramMap, accessors2, enums2, fields2) <- buildVarMap (stsJsonParams json)
let accMap = accessors1 <> accessors2
let enums = enums1 <> enums2
initVal <- buildValuation locVarMap (stsJsonInitValuation json) enums
let varMap = locVarMap `Map.union` paramMap
inputGateMap <- buildGateMap In varMap (stsJsonInputGates json)
outputGateMap <- buildGateMap Out varMap (stsJsonOutputGates json)
let gateMap = inputGateMap `Map.union` outputGateMap
alphabet = Set.fromList (Map.elems gateMap)
guardMap' <- traverse (toExpr varMap accMap enums) (stsJsonGuards json)
guardMap <- traverse (\(tp :=> e) -> case tp of
BoolType -> Right e
_ -> Left "guard with non-bool type") guardMap'
assignMap <- buildAssignmentMap varMap accMap enums (stsJsonAssignments json)
switchList <- buildSwitchList gateMap guardMap assignMap (stsJsonSwitches json)
let transRel = buildTransitionRel switchList
initCfg = atom $ locId (stsJsonInitLoc json)
sts = automaton initCfg alphabet transRel
return (stsJsonId json, sts, guardMap, Map.map ($ noAssignment) assignMap, initVal, enums, unionAttrNames fields1 fields2)
{-|
Read a JSON file and parse an STS from it. Returns a tuple (ID, STS, Initial Valuation) if successful,
or an error message if parsing fails.
-}
stsFromJSONFile :: FilePath -> IO (Either String STSParseResult)
stsFromJSONFile path = do
bytes <- BSL.readFile path
return $ case JSON.eitherDecode bytes of
Left err -> Left $ "JSON decode error: " ++ err
Right stsJson -> convertSTSJson stsJson
{-|
Read a JSON file containing a list of STSs, and parse each one.
-}
stsListFromJSONFile :: FilePath -> IO (Either String [STSParseResult])
stsListFromJSONFile path = do
bytes <- BSL.readFile path
return $ case JSON.eitherDecode bytes of
Left err -> Left $ "JSON decode error: " ++ err
Right stsJsons -> forM stsJsons convertSTSJson
instance JSON.FromJSON AlgReal where
-- convert from the decimal JSON number directly
parseJSON = JSON.withScientific "real" (pure . fromRational . toRational)