claferIG 0.4.5 → 0.5.8
raw patch · 24 files changed
+2087/−531 lines, 24 filesdep +aesondep +exceptionsdep −HUnitdep −arraydep −data-stringmapdep ~basedep ~claferdep ~claferIGPVP ok
version bump matches the API change (PVP)
Dependencies added: aeson, exceptions
Dependencies removed: HUnit, array, data-stringmap, json-builder, mtl-compat, transformers-compat
Dependency ranges changed: base, clafer, claferIG, haskeline, transformers
API changes (from Hackage documentation)
- Language.Clafer.IG.AlloyIGInterface: data UnsatCore
- Language.Clafer.IG.AlloyIGInterface: instance System.Console.Haskeline.MonadException.MonadException m => System.Console.Haskeline.MonadException.MonadException (Language.Clafer.IG.AlloyIGInterface.AlloyIGT m)
- Language.Clafer.IG.ClaferIG: [modelInstance] :: Instance -> ClaferModel
- Language.Clafer.IG.ClaferIG: instance System.Console.Haskeline.MonadException.MonadException m => System.Console.Haskeline.MonadException.MonadException (Language.Clafer.IG.ClaferIG.ClaferIGT m)
+ Language.Clafer.IG.AlloyIGInterface: instance Control.Monad.Catch.MonadCatch m => Control.Monad.Catch.MonadCatch (Language.Clafer.IG.AlloyIGInterface.AlloyIGT m)
+ Language.Clafer.IG.AlloyIGInterface: instance Control.Monad.Catch.MonadMask m => Control.Monad.Catch.MonadMask (Language.Clafer.IG.AlloyIGInterface.AlloyIGT m)
+ Language.Clafer.IG.AlloyIGInterface: instance Control.Monad.Catch.MonadThrow m => Control.Monad.Catch.MonadThrow (Language.Clafer.IG.AlloyIGInterface.AlloyIGT m)
+ Language.Clafer.IG.AlloyIGInterface: newSessionTmpdir :: IO FilePath
+ Language.Clafer.IG.AlloyIGInterface: newtype UnsatCore
+ Language.Clafer.IG.AlloyIGInterface: sendCheckCommand :: forall (m :: Type -> Type). MonadIO m => String -> AlloyIGT m (Maybe String)
+ Language.Clafer.IG.AlloyIGInterface: sendForkCommand :: forall (m :: Type -> Type). MonadIO m => Integer -> AlloyIGT m (Maybe String)
+ Language.Clafer.IG.AlloyIGInterface: sendNextConfigurationCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m (Maybe String)
+ Language.Clafer.IG.AlloyIGInterface: sendSetMaxTraceLengthCommand :: forall (m :: Type -> Type). MonadIO m => Integer -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sessionTmpdir :: forall (m :: Type -> Type). Monad m => AlloyIGT m FilePath
+ Language.Clafer.IG.ClaferIG: [alloyNameMap] :: ClaferIGEnv -> Map UID String
+ Language.Clafer.IG.ClaferIG: [diff] :: IGArgs -> Bool
+ Language.Clafer.IG.ClaferIG: [dot] :: IGArgs -> Bool
+ Language.Clafer.IG.ClaferIG: [dynamicModel] :: ClaferIGEnv -> Bool
+ Language.Clafer.IG.ClaferIG: [emptySigs] :: ClaferIGEnv -> Set String
+ Language.Clafer.IG.ClaferIG: [import_base_comp] :: IGArgs -> String
+ Language.Clafer.IG.ClaferIG: [import_root_comp] :: IGArgs -> [FilePath]
+ Language.Clafer.IG.ClaferIG: [imports_comp] :: IGArgs -> [FilePath]
+ Language.Clafer.IG.ClaferIG: [maxInstances] :: IGArgs -> Maybe Integer
+ Language.Clafer.IG.ClaferIG: [modelFileName] :: ClaferIGEnv -> FilePath
+ Language.Clafer.IG.ClaferIG: [modelFiles] :: ClaferIGEnv -> [ModelFile]
+ Language.Clafer.IG.ClaferIG: [modelSolution] :: Instance -> ClaferSolution
+ Language.Clafer.IG.ClaferIG: [public_imports_comp] :: IGArgs -> Bool
+ Language.Clafer.IG.ClaferIG: [tl_comp] :: IGArgs -> Maybe Integer
+ Language.Clafer.IG.ClaferIG: checkAssertion :: forall (m :: Type -> Type). MonadIO m => String -> ClaferIGT m (Maybe (ClaferSolution, String))
+ Language.Clafer.IG.ClaferIG: claferNameOfSig :: forall (m :: Type -> Type). MonadIO m => String -> ClaferIGT m String
+ Language.Clafer.IG.ClaferIG: fork :: forall (m :: Type -> Type). MonadIO m => Integer -> ClaferIGT m Instance
+ Language.Clafer.IG.ClaferIG: getAssertions :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m [(String, ConstraintInfo)]
+ Language.Clafer.IG.ClaferIG: getModelFileName :: forall (m :: Type -> Type). Monad m => ClaferIGT m FilePath
+ Language.Clafer.IG.ClaferIG: getModelFiles :: forall (m :: Type -> Type). Monad m => ClaferIGT m [ModelFile]
+ Language.Clafer.IG.ClaferIG: getSessionTmpdir :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m FilePath
+ Language.Clafer.IG.ClaferIG: getToUid :: forall (m :: Type -> Type). Monad m => ClaferIGT m (String -> String)
+ Language.Clafer.IG.ClaferIG: hasNoInstances :: forall (m :: Type -> Type). Monad m => String -> ClaferIGT m Bool
+ Language.Clafer.IG.ClaferIG: instance Control.Monad.Catch.MonadCatch m => Control.Monad.Catch.MonadCatch (Language.Clafer.IG.ClaferIG.ClaferIGT m)
+ Language.Clafer.IG.ClaferIG: instance Control.Monad.Catch.MonadMask m => Control.Monad.Catch.MonadMask (Language.Clafer.IG.ClaferIG.ClaferIGT m)
+ Language.Clafer.IG.ClaferIG: instance Control.Monad.Catch.MonadThrow m => Control.Monad.Catch.MonadThrow (Language.Clafer.IG.ClaferIG.ClaferIGT m)
+ Language.Clafer.IG.ClaferIG: isDynamicModel :: forall (m :: Type -> Type). Monad m => ClaferIGT m Bool
+ Language.Clafer.IG.ClaferIG: nextConfiguration :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m Instance
+ Language.Clafer.IG.ClaferIG: setMaxTraceLength :: forall (m :: Type -> Type). MonadIO m => Integer -> ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: sigOfUID :: forall (m :: Type -> Type). Monad m => UID -> ClaferIGT m String
+ Language.Clafer.IG.ClaferIG: uidOfSig :: forall (m :: Type -> Type). Monad m => String -> ClaferIGT m UID
+ Language.Clafer.IG.ClaferModel: ClaferInstance :: ClaferModel -> ClaferSolution
+ Language.Clafer.IG.ClaferModel: ClaferTrace :: [ClaferModel] -> Int -> ClaferSolution
+ Language.Clafer.IG.ClaferModel: [c_uid] :: Clafer -> String
+ Language.Clafer.IG.ClaferModel: buildStateModel :: Solution -> ClaferModel
+ Language.Clafer.IG.ClaferModel: data ClaferSolution
+ Language.Clafer.IG.ClaferModel: solutionModels :: ClaferSolution -> [ClaferModel]
+ Language.Clafer.IG.CommandLineParser: Check :: Maybe Integer -> Command
+ Language.Clafer.IG.CommandLineParser: Fork :: Integer -> Command
+ Language.Clafer.IG.CommandLineParser: NextConfiguration :: Command
+ Language.Clafer.IG.CommandLineParser: SaveGraph :: Command
+ Language.Clafer.IG.CommandLineParser: SetMaxTraceLength :: Integer -> Command
+ Language.Clafer.IG.CommandLineParser: ToggleDiff :: Command
+ Language.Clafer.IG.Constraints: [fileLine] :: ConstraintInfo -> Integer
+ Language.Clafer.IG.Constraints: [position] :: ConstraintInfo -> String
+ Language.Clafer.IG.Constraints: isOnLine :: Integer -> ConstraintInfo -> Bool
+ Language.Clafer.IG.Constraints: parseAssertions :: [ModelFile] -> IModule -> [(String, ConstraintInfo)]
+ Language.Clafer.IG.Solution: parseTrace :: String -> ([Solution], Int)
+ Language.Clafer.IG.SolutionView: instance GHC.Classes.Eq Language.Clafer.IG.SolutionView.Entry
+ Language.Clafer.IG.SolutionView: instance GHC.Classes.Ord Language.Clafer.IG.SolutionView.Entry
+ Language.Clafer.IG.SolutionView: lpqName :: QNameMaps -> String -> String
+ Language.Clafer.IG.SolutionView: showSolution :: Int -> ClaferSolution -> String
+ Language.Clafer.IG.SolutionView: showSolutionDiff :: (String -> String) -> Int -> Maybe ClaferSolution -> ClaferSolution -> String
+ Language.Clafer.IG.SolutionView: solutionDiffDot :: (String -> String) -> ClaferSolution -> String
+ Language.Clafer.IG.SolutionView: solutionDot :: ClaferSolution -> String
+ Language.Clafer.IG.SolutionView: solutionJSON :: UIDIClaferMap -> ClaferSolution -> String
+ Language.Clafer.IG.SolutionView: solutionText :: ClaferSolution -> String
+ Language.Clafer.IG.Sugarer: sugarClaferStates :: (String -> String) -> Bool -> Bool -> UIDIClaferMap -> [ClaferModel] -> Map Int String -> [ClaferModel]
- Language.Clafer.IG.AlloyIGInterface: AlloyIGT :: (StateT (Maybe AlloyIGEnv) (ReaderT Process m) a) -> AlloyIGT m a
+ Language.Clafer.IG.AlloyIGInterface: AlloyIGT :: StateT (Maybe AlloyIGEnv) (ReaderT (Process, FilePath) m) a -> AlloyIGT (m :: Type -> Type) a
- Language.Clafer.IG.AlloyIGInterface: fetch :: Monad m => AlloyIGT m AlloyIGEnv
+ Language.Clafer.IG.AlloyIGInterface: fetch :: forall (m :: Type -> Type). Monad m => AlloyIGT m AlloyIGEnv
- Language.Clafer.IG.AlloyIGInterface: fetches :: Monad m => (AlloyIGEnv -> a) -> AlloyIGT m a
+ Language.Clafer.IG.AlloyIGInterface: fetches :: forall (m :: Type -> Type) a. Monad m => (AlloyIGEnv -> a) -> AlloyIGT m a
- Language.Clafer.IG.AlloyIGInterface: getAlloyModel :: MonadIO m => AlloyIGT m String
+ Language.Clafer.IG.AlloyIGInterface: getAlloyModel :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m String
- Language.Clafer.IG.AlloyIGInterface: getGlobalScope :: MonadIO m => AlloyIGT m Integer
+ Language.Clafer.IG.AlloyIGInterface: getGlobalScope :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m Integer
- Language.Clafer.IG.AlloyIGInterface: getMsg :: MonadIO m => AlloyIGT m String
+ Language.Clafer.IG.AlloyIGInterface: getMsg :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m String
- Language.Clafer.IG.AlloyIGInterface: getScope :: MonadIO m => String -> AlloyIGT m Integer
+ Language.Clafer.IG.AlloyIGInterface: getScope :: forall (m :: Type -> Type). MonadIO m => String -> AlloyIGT m Integer
- Language.Clafer.IG.AlloyIGInterface: getScopes :: MonadIO m => AlloyIGT m [(String, Integer)]
+ Language.Clafer.IG.AlloyIGInterface: getScopes :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m [(String, Integer)]
- Language.Clafer.IG.AlloyIGInterface: getSigs :: MonadIO m => AlloyIGT m [String]
+ Language.Clafer.IG.AlloyIGInterface: getSigs :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m [String]
- Language.Clafer.IG.AlloyIGInterface: newtype AlloyIGT m a
+ Language.Clafer.IG.AlloyIGInterface: newtype AlloyIGT (m :: Type -> Type) a
- Language.Clafer.IG.AlloyIGInterface: proc :: Monad m => AlloyIGT m Process
+ Language.Clafer.IG.AlloyIGInterface: proc :: forall (m :: Type -> Type). Monad m => AlloyIGT m Process
- Language.Clafer.IG.AlloyIGInterface: putMsg :: MonadIO m => String -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: putMsg :: forall (m :: Type -> Type). MonadIO m => String -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: readMsg :: (MonadIO m, Read r) => AlloyIGT m r
+ Language.Clafer.IG.AlloyIGInterface: readMsg :: forall (m :: Type -> Type) r. (MonadIO m, Read r) => AlloyIGT m r
- Language.Clafer.IG.AlloyIGInterface: sendLoadCommand :: MonadIO m => String -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendLoadCommand :: forall (m :: Type -> Type). MonadIO m => String -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendNextCommand :: MonadIO m => AlloyIGT m (Maybe String)
+ Language.Clafer.IG.AlloyIGInterface: sendNextCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m (Maybe String)
- Language.Clafer.IG.AlloyIGInterface: sendQuitCommand :: MonadIO m => AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendQuitCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendRemoveConstraintCommand :: MonadIO m => Span -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendRemoveConstraintCommand :: forall (m :: Type -> Type). MonadIO m => Span -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendResolveCommand :: MonadIO m => AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendResolveCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendRestoreStateCommand :: MonadIO m => AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendRestoreStateCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendSaveStateCommand :: MonadIO m => AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendSaveStateCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendSetBitwidthCommand :: MonadIO m => Integer -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendSetBitwidthCommand :: forall (m :: Type -> Type). MonadIO m => Integer -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendSetGlobalScopeCommand :: MonadIO m => Integer -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendSetGlobalScopeCommand :: forall (m :: Type -> Type). MonadIO m => Integer -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendSetScopeCommand :: MonadIO m => String -> Integer -> AlloyIGT m (Maybe String)
+ Language.Clafer.IG.AlloyIGInterface: sendSetScopeCommand :: forall (m :: Type -> Type). MonadIO m => String -> Integer -> AlloyIGT m (Maybe String)
- Language.Clafer.IG.AlloyIGInterface: sendSetUnsatCoreMinimizationCommand :: MonadIO m => Integer -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: sendSetUnsatCoreMinimizationCommand :: forall (m :: Type -> Type). MonadIO m => Integer -> AlloyIGT m ()
- Language.Clafer.IG.AlloyIGInterface: sendUnsatCoreCommand :: MonadIO m => AlloyIGT m UnsatCore
+ Language.Clafer.IG.AlloyIGInterface: sendUnsatCoreCommand :: forall (m :: Type -> Type). MonadIO m => AlloyIGT m UnsatCore
- Language.Clafer.IG.AlloyIGInterface: set :: Monad m => AlloyIGEnv -> AlloyIGT m ()
+ Language.Clafer.IG.AlloyIGInterface: set :: forall (m :: Type -> Type). Monad m => AlloyIGEnv -> AlloyIGT m ()
- Language.Clafer.IG.ClaferIG: ClaferIGEnv :: ClaferEnv -> IGArgs -> [Constraint] -> String -> QNameMaps -> UIDIClaferMap -> Map Int String -> Map Integer String -> ClaferIGEnv
+ Language.Clafer.IG.ClaferIG: ClaferIGEnv :: ClaferEnv -> IGArgs -> [Constraint] -> String -> [ModelFile] -> FilePath -> QNameMaps -> UIDIClaferMap -> Map Int String -> Map Integer String -> Bool -> Set String -> Map UID String -> ClaferIGEnv
- Language.Clafer.IG.ClaferIG: ClaferIGT :: (StateT ClaferIGEnv (AlloyIGT m) a) -> ClaferIGT m a
+ Language.Clafer.IG.ClaferIG: ClaferIGT :: StateT ClaferIGEnv (AlloyIGT m) a -> ClaferIGT (m :: Type -> Type) a
- Language.Clafer.IG.ClaferIG: Counterexample :: [Constraint] -> ClaferModel -> String -> Counterexample
+ Language.Clafer.IG.ClaferIG: Counterexample :: [Constraint] -> ClaferSolution -> String -> Counterexample
- Language.Clafer.IG.ClaferIG: IGArgs :: Maybe Integer -> Maybe FilePath -> FilePath -> FilePath -> Integer -> Integer -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> ScopeStrategy -> IGArgs
+ Language.Clafer.IG.ClaferIG: IGArgs :: Maybe Integer -> Maybe Integer -> Maybe FilePath -> FilePath -> [FilePath] -> [FilePath] -> Bool -> String -> FilePath -> Integer -> Integer -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe Integer -> Bool -> Bool -> Bool -> Bool -> ScopeStrategy -> IGArgs
- Language.Clafer.IG.ClaferIG: Instance :: ClaferModel -> String -> Instance
+ Language.Clafer.IG.ClaferIG: Instance :: ClaferSolution -> String -> Instance
- Language.Clafer.IG.ClaferIG: [counterexampleInstance] :: Counterexample -> ClaferModel
+ Language.Clafer.IG.ClaferIG: [counterexampleInstance] :: Counterexample -> ClaferSolution
- Language.Clafer.IG.ClaferIG: getAlloyModel :: MonadIO m => ClaferIGT m String
+ Language.Clafer.IG.ClaferIG: getAlloyModel :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m String
- Language.Clafer.IG.ClaferIG: getBitwidth :: MonadIO m => ClaferIGT m Integer
+ Language.Clafer.IG.ClaferIG: getBitwidth :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m Integer
- Language.Clafer.IG.ClaferIG: getClaferEnv :: Monad m => ClaferIGT m ClaferEnv
+ Language.Clafer.IG.ClaferIG: getClaferEnv :: forall (m :: Type -> Type). Monad m => ClaferIGT m ClaferEnv
- Language.Clafer.IG.ClaferIG: getClaferIGArgs :: Monad m => ClaferIGT m IGArgs
+ Language.Clafer.IG.ClaferIG: getClaferIGArgs :: forall (m :: Type -> Type). Monad m => ClaferIGT m IGArgs
- Language.Clafer.IG.ClaferIG: getClaferModel :: Monad m => ClaferIGT m String
+ Language.Clafer.IG.ClaferIG: getClaferModel :: forall (m :: Type -> Type). Monad m => ClaferIGT m String
- Language.Clafer.IG.ClaferIG: getClafers :: MonadIO m => ClaferIGT m [String]
+ Language.Clafer.IG.ClaferIG: getClafers :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m [String]
- Language.Clafer.IG.ClaferIG: getConstraints :: Monad m => ClaferIGT m [Constraint]
+ Language.Clafer.IG.ClaferIG: getConstraints :: forall (m :: Type -> Type). Monad m => ClaferIGT m [Constraint]
- Language.Clafer.IG.ClaferIG: getGlobalScope :: MonadIO m => ClaferIGT m Integer
+ Language.Clafer.IG.ClaferIG: getGlobalScope :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m Integer
- Language.Clafer.IG.ClaferIG: getQNameMaps :: MonadIO m => ClaferIGT m (QNameMaps)
+ Language.Clafer.IG.ClaferIG: getQNameMaps :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m QNameMaps
- Language.Clafer.IG.ClaferIG: getScope :: MonadIO m => QName -> ClaferIGT m ([String])
+ Language.Clafer.IG.ClaferIG: getScope :: forall (m :: Type -> Type). MonadIO m => QName -> ClaferIGT m [String]
- Language.Clafer.IG.ClaferIG: getScopes :: MonadIO m => ClaferIGT m [(String, Integer)]
+ Language.Clafer.IG.ClaferIG: getScopes :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m [(String, Integer)]
- Language.Clafer.IG.ClaferIG: getStrMap :: Monad m => ClaferIGT m (Map Int String)
+ Language.Clafer.IG.ClaferIG: getStrMap :: forall (m :: Type -> Type). Monad m => ClaferIGT m (Map Int String)
- Language.Clafer.IG.ClaferIG: getUIDIClaferMap :: Monad m => ClaferIGT m UIDIClaferMap
+ Language.Clafer.IG.ClaferIG: getUIDIClaferMap :: forall (m :: Type -> Type). Monad m => ClaferIGT m UIDIClaferMap
- Language.Clafer.IG.ClaferIG: getlineNumMap :: Monad m => ClaferIGT m (Map Integer String)
+ Language.Clafer.IG.ClaferIG: getlineNumMap :: forall (m :: Type -> Type). Monad m => ClaferIGT m (Map Integer String)
- Language.Clafer.IG.ClaferIG: increaseScope :: MonadIO m => Integer -> (String, Integer) -> ClaferIGT m (Either String ())
+ Language.Clafer.IG.ClaferIG: increaseScope :: forall (m :: Type -> Type). MonadIO m => Integer -> (String, Integer) -> ClaferIGT m (Either String ())
- Language.Clafer.IG.ClaferIG: newtype ClaferIGT m a
+ Language.Clafer.IG.ClaferIG: newtype ClaferIGT (m :: Type -> Type) a
- Language.Clafer.IG.ClaferIG: next :: MonadIO m => ClaferIGT m Instance
+ Language.Clafer.IG.ClaferIG: next :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m Instance
- Language.Clafer.IG.ClaferIG: quit :: MonadIO m => ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: quit :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m ()
- Language.Clafer.IG.ClaferIG: reload :: MonadIO m => ClaferIGT m (Either ClaferErrs ())
+ Language.Clafer.IG.ClaferIG: reload :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m (Either ClaferErrs ())
- Language.Clafer.IG.ClaferIG: setAlloyScope :: MonadIO m => Integer -> String -> ClaferIGT m (Either String ())
+ Language.Clafer.IG.ClaferIG: setAlloyScope :: forall (m :: Type -> Type). MonadIO m => Integer -> String -> ClaferIGT m (Either String ())
- Language.Clafer.IG.ClaferIG: setBitwidth :: MonadIO m => Integer -> ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: setBitwidth :: forall (m :: Type -> Type). MonadIO m => Integer -> ClaferIGT m ()
- Language.Clafer.IG.ClaferIG: setGlobalScope :: MonadIO m => Integer -> ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: setGlobalScope :: forall (m :: Type -> Type). MonadIO m => Integer -> ClaferIGT m ()
- Language.Clafer.IG.ClaferIG: setScope :: MonadIO m => Integer -> (String, Integer) -> ClaferIGT m (Either String ())
+ Language.Clafer.IG.ClaferIG: setScope :: forall (m :: Type -> Type). MonadIO m => Integer -> (String, Integer) -> ClaferIGT m (Either String ())
- Language.Clafer.IG.ClaferIG: setUnsatCoreMinimization :: MonadIO m => Integer -> ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: setUnsatCoreMinimization :: forall (m :: Type -> Type). MonadIO m => Integer -> ClaferIGT m ()
- Language.Clafer.IG.ClaferIG: solve :: MonadIO m => ClaferIGT m ()
+ Language.Clafer.IG.ClaferIG: solve :: forall (m :: Type -> Type). MonadIO m => ClaferIGT m ()
- Language.Clafer.IG.ClaferIG: valueOfScope :: MonadIO m => String -> ClaferIGT m Integer
+ Language.Clafer.IG.ClaferIG: valueOfScope :: forall (m :: Type -> Type). MonadIO m => String -> ClaferIGT m Integer
- Language.Clafer.IG.ClaferModel: Clafer :: Id -> Maybe Value -> [Clafer] -> Clafer
+ Language.Clafer.IG.ClaferModel: Clafer :: Id -> String -> Maybe Value -> [Clafer] -> Clafer
- Language.Clafer.IG.Constraints: ConstraintInfo :: String -> Span -> String -> ConstraintInfo
+ Language.Clafer.IG.Constraints: ConstraintInfo :: String -> Span -> String -> String -> Integer -> ConstraintInfo
- Language.Clafer.IG.Constraints: parseConstraints :: String -> IModule -> [(Span, IrTrace)] -> [Constraint]
+ Language.Clafer.IG.Constraints: parseConstraints :: [ModelFile] -> IModule -> [(Span, IrTrace)] -> [Constraint]
- Language.Clafer.IG.Process: pipeProcess :: FilePath -> [String] -> IO Process
+ Language.Clafer.IG.Process: pipeProcess :: FilePath -> [String] -> [(String, String)] -> IO Process
- Language.Clafer.IG.Sugarer: sugarClaferModel :: Bool -> Bool -> UIDIClaferMap -> ClaferModel -> (Map Int String) -> ClaferModel
+ Language.Clafer.IG.Sugarer: sugarClaferModel :: (String -> String) -> Bool -> Bool -> UIDIClaferMap -> ClaferModel -> Map Int String -> ClaferModel
Files
- CHANGES.md +81/−0
- LICENSE +2/−1
- Makefile +39/−55
- README.md +262/−110
- alloyIG.jar binary
- claferIG.cabal +57/−58
- lib/libminisatprover.dylib binary
- lib/libminisatprover.so binary
- lib/minisatprover.dll binary
- src-cmd/Main.hs +46/−19
- src/Language/Clafer/IG/AlloyIGInterface.hs +84/−9
- src/Language/Clafer/IG/ClaferIG.hs +210/−48
- src/Language/Clafer/IG/ClaferModel.hs +36/−12
- src/Language/Clafer/IG/CommandLine.hs +205/−73
- src/Language/Clafer/IG/CommandLineParser.hs +24/−0
- src/Language/Clafer/IG/Constraints.hs +55/−13
- src/Language/Clafer/IG/JSONGenerator.hs +20/−14
- src/Language/Clafer/IG/Process.hs +4/−4
- src/Language/Clafer/IG/Solution.hs +21/−1
- src/Language/Clafer/IG/SolutionView.hs +213/−0
- src/Language/Clafer/IG/Sugarer.hs +54/−33
- stack.yaml +15/−7
- test/model-tests.hs +659/−0
- test/test-suite.hs +0/−74
CHANGES.md view
@@ -1,3 +1,84 @@+##### ClaferIG Version 0.5.8, Nov 15, 2026++Minor release with Clafer 0.5.8.++* Builds with GHC 9.12.4 (Stackage nightly-2026-11-11) and still with GHC 9.6.7.+* The model tests run on 8 cores (`+RTS -N8`): with GHC 9.12, the test suite hung on 16 or more cores, in the parallel garbage collector. They take about 30 seconds, as on all cores before.+* No longer depends on `data-stringmap`: the scopes are a `Data.Map` map.+* No longer depends on `json-builder`, which is not maintained and does not build from Hackage with GHC 8.4 or later: the JSON instances (`--json`) are written with `aeson`'s encoding, field by field in the same order. The instances of the positive test models are the same.+* Depends only on the packages it uses: `mtl-compat` and `transformers-compat` are no longer dependencies, `array` no longer of the library, and `HUnit` no longer of the test suites.++##### ClaferIG Version 0.5.7, Nov 8, 2026++Minor release with Clafer 0.5.7.++* The UIDs of the clafers are their names since Clafer 0.5.7, qualified only where a name is not unique (`x__size`), and the Alloy model renames those that cannot be Alloy names (e.g., `sig_1` for `sig`). claferIG shows the names of the clafers, also with `--useuids` (their UIDs, not their Alloy names), and takes UIDs in its commands and scope files (`i sig 3`, `saveScopes`, `loadScopes`); it translates between the UIDs and the Alloy names. It cut a sig's name after its first `_` when a clafer was not found.+* Dynamic models: the obligations of a constraint last while the parent of its context exists, so a transition nested in its source state, e.g., `[ req=down --> movingDown ]` in the state `movingUp`, takes the machine to its target ([clafer#107](https://github.com/gsdlab/clafer/issues/107)).+* Dynamic models: a negated obligation lapses with the parent too, so `[ !(F error) ]` lets the parent disappear, like `[ G !error ]` ([clafer#110](https://github.com/gsdlab/clafer/issues/110)).+* Unsat cores have the constraints of abstract clafers and of their children, each at its position in the model ([#46](https://github.com/gsdlab/claferIG/issues/46)). Alloy gave the position of the whole signature for a constraint of a signature that is not a `one sig`, which matched no constraint of the model: such constraints were left out of the core, and a model whose constraints were all in abstract clafers gave "No more instances found" without a core.+* The next trace, `fork` and `config` are solved without logging the translation for an unsat core, as `check` was: they give no core. The log of a large model took gigabytes, e.g., 11 GB in 3 minutes for the next trace of the TLS handshake model, and filled the temporary folder of a session; the first solution, which gives the core of a model with no instances, still logs it.+* The next trace, `fork` and `config` differ from the traces given so far in what the traces show. The reference of a clafer that is not in a state has any value there, and a trace that differed from the last one only in such a value was given as a new trace that looked the same, e.g., the same trace of the WebSocket model again and again.+* An abstract clafer that no concrete clafer inherits from, and the clafers in it, have no instances: their scopes stay 0 when the scopes are raised, with `i`, `i <clafer>`, `s <clafer> <number>`, a `.cfr-scope` file or a reload, and `i <clafer>` and `s <clafer> <number>` say so. Raising them gave Alloy atoms of such clafers, which made a model, e.g., the power window with abstract variants of its controller, take minutes instead of seconds.+* Ending a session no longer prints a `NoSuchFileException` when Alloy removes its own temporary files while claferIG removes the session's folder.+* The model tests check the scopes of the patterns `must follow ... between` and `must precede ... after`, and that `finaltarget` lets the instances of a clafer swap their targets, while `finalref` and `final` do not ([kbak/clafer-semantics#127](https://github.com/kbak/clafer-semantics/issues/127)).+* The model tests run in parallel, on all cores, each in a folder of its own (two tests wrote different `lib.cfr` files into one folder); the lifetimes, pattern scope and `finaltarget` tests are split into one test for each case. `make test` takes about 30 seconds instead of 2 minutes.+* The model tests check the lifetimes of obligations, the identities in a scope and the parent of a reappearing instance, with both scope strategies, at the scopes 1 to 3 and up to 3 and 10 states, and that the scopes of abstract clafers without instances stay 0.+* The model test `SessionTmpdir` checks that only the first solve logs the translation of the model, not the next trace, a fork or another configuration, and that the session's folder is removed when the session ends.++##### ClaferIG Version 0.5.6, Nov 1, 2026++Minor release with Clafer 0.5.6.++* Dynamic models, with temporal operators or the temporal modifiers `initial` and `final`: their solutions are traces, whose states are instances. `n` gives the next solution, an instance of a static model or a trace of a dynamic model, with its states (`--- State 0 ---`) and the state to which it loops back (`--- Loop back to state 3 ---`). An instance has the same name in all the states of a trace. claferIG refused dynamic models.+* The traces are given from the shortest, each different from the traces given before, regardless of the names of their atoms, up to the maximum trace length: `--tl` and the command `tl <number>` (by default, 10 states). Alloy 6.2 enumerates only a few traces of a temporal model, or none, so claferIG solves for each next trace without the traces given before.+* Diff view: `--diff`, or the command `d`, shows the first instance or state with `+` on each line, and each next one as its changes from the previous one: the clafers that appear (`+`), with their children, that disappear (`-`), and the values that change (`~`), each indented as in the tree and with its least-partially-qualified name, e.g., `normal.yellow`. The instances of a static model are compared by their structure.+* `--all` saves each trace to its own file, `--json` gives a trace as `{"states": [...], "loop": 3}`, and `f` finds a clafer in all the states of the most recent trace.+* `fork <number>` gives another trace with the same states as the last trace before the given state, and `config` a trace whose clafers that do not change over time, e.g., `final` features, differ from those of the traces given so far.+* The command `config` also works on static models: an instance whose structure, its clafers without the values of their references, differs from those of the instances given so far.+* The command `check` checks the assertions of the model within the scopes and the maximum trace length, and gives a counterexample of each one that fails; `check <number>` checks only the assertions on that line ([#30](https://github.com/gsdlab/claferIG/issues/30)). claferIG ignored assertions.+* The command `dot` saves the most recent solution as a Graphviz graph, for a trace its states and transitions, and `--dot` gives the solutions as such graphs. In the diff view, the states of the graph show their changes.+* Unsat cores: a model with no instances, or a dynamic model with no traces, gives the constraints that contradict each other and a near-miss example. claferIG gave no unsat core when Alloy found the model unsatisfiable without solving, e.g., for `[ some b ]` and `[ no b ]`, and for dynamic models. The constraints are shown with the right text when their lines are indented with tabs, and with the parentheses that close them, e.g., `initially (green --> red)`.+* `-n` limits the number of instances that `--all` saves, as chocosolver's `-n` does, e.g., `claferIG --all -n 2 model.cfr` to check whether a model has exactly one instance ([#43](https://github.com/gsdlab/claferIG/issues/43)).+* Each session keeps the temporary files of Alloy in a folder of its own, which is removed when it ends, also when claferIG is killed. Kodkod's logs stayed in the temporary folder of the system, and those of large models filled it.++##### ClaferIG Version 0.5.5, Oct 27, 2026++Minor release with Clafer 0.5.5.++* A model that Alloy does not support, e.g., with decimals, reals or doubles, is refused with the compiler's reason ("Alloy output unavailable because the model contains: a decimal literal, ..."); claferIG crashed with "No match in record selector extension". Decimals are supported by the Choco backend (chocosolver) only.+* The errors before "Press enter to retry." are flushed, so a tool reading claferIG's output through a pipe, e.g., ClaferIDE, shows them; it showed nothing and waited.+* A `.cfr-scope` file may list only some clafers, without the global scope (`"lpqName": ""`), e.g., `[{"lpqName": "Component::Cfeatures", "scope": 132}]`: `loadScopes` keeps the global scope and `--all` uses the given one. Such a file crashed claferIG with "Prelude.maximum: empty list". chocosolver 0.5.5 reads the same files.++##### ClaferIG Version 0.5.4, Oct 25, 2026++Minor release with Clafer 0.5.4.++* Models in several files: `--import=FILE`, in the model's `//# OPTIONS` or on the command line, generates instances of the model together with the imported files, as with the Clafer compiler ([gsdlab/clafer#100](https://github.com/gsdlab/clafer/issues/100)). The model and its imports can be URLs; the saved files are named after a URL's last segment.+* `--import-root=DIR`, `--public-imports` and `--import-base=URL` restrict the imports of a model that may come from anyone, as with the compiler (e.g., in a web tool); they can only be given on the command line.+* The options in the model's `//# OPTIONS` directive apply, as they do with the compiler: the layout, the scope strategy, and the other options of the compilation. The integer range of `--maxint` and `--minint` raises the bitwidth when it needs a larger one.+* Positions are given as `file.cfr:line:column`, the file in which they are, also in a model of one file: errors are reported as by the compiler (`Parse failed at model.cfr:3:5...`, `Compile error at ...`, `Error...`, then the message), and the constraints of an unsatisfiable core give their position (`x < 2 (model.cfr:4:7)`, previously `(line 4, column 7)`). The command `c` (`claferModel`) shows each file under its name, with the numbers of its lines.+* The command `c` (`claferModel`) shows the scope of the model's first clafer; its line had no scope, and the line of its first child showed the first clafer's scope instead of the child's.+* Instances show the clafers' names from the model instead of names derived from their UIDs, which differ for names with apostrophes (`same'` has the UID `c0_same__prime__`). This also applies to the clafer names in scope messages.+* [Release](https://github.com/gsdlab/claferIG/pull/38)++##### ClaferIG Version 0.5.3, Oct 15, 2026++Minor release with Clafer 0.5.3 and Alloy 6.2.0.++* Uses Alloy 6.2.0 (`alloy6.2.0.jar`, Java 17+) instead of Alloy 4.2. The MiniSat solver with UnSAT cores is part of the Alloy jar on Linux and macOS (Intel and ARM); on Windows there is none, so instances come from SAT4J and there are no UnSAT cores.+* The MiniSat solver in Alloy 6.2.0 is built without optimization and is several times slower ([AlloyTools/org.alloytools.alloy#352](https://github.com/AlloyTools/org.alloytools.alloy/issues/352)). `make` builds it with optimization into `lib/` (needs `cmake`), and ClaferIG uses that build when it is next to the executable.+* Works around an Alloy 6.2.0 bug that made every UnSAT core empty (the MiniSat prover is freed before its proof is read; fixed in Alloy after 6.2.0).+* The tests that need the example models and Alloy run in the `model-tests` suite (flag `model-tests`, off by default) and are not part of the package.+* [Release](https://github.com/gsdlab/claferIG/pull/37)++##### ClaferIG Version 0.5.2 released on Oct 9, 2026++* [Release](https://github.com/gsdlab/claferIG/pull/36)++##### ClaferIG Version 0.5.1 released on Sep 12, 2023++* [Release](https://github.com/gsdlab/claferIG/pull/35)+ ##### ClaferIG Version 0.4.5 released on Mar 13, 2017 * [Release](https://github.com/gsdlab/claferIG/pull/33)
LICENSE view
@@ -1,4 +1,5 @@-Copyright 2012-2017 Generative Software Development Lab <http://gsd.uwaterloo.ca>+Copyright 2012-2019 Generative Software Development Lab <http://gsd.uwaterloo.ca>+Copyright 2019-2023 Intelligent Systems Development Lab <https://uwaterloo.ca/wise-lab/> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in
Makefile view
@@ -2,35 +2,29 @@ EXE := .exe endif -ifeq ($(OS),Windows_NT)- LIB := x86-windows/minisatprover*+ALLOY_JAR := alloy6.2.0.jar+ALLOY_URL := https://github.com/AlloyTools/org.alloytools.alloy/releases/download/v6.2.0/org.alloytools.alloy.dist.jar++# The MiniSat prover built with optimization (see native/minisatprover/CMakeLists.txt).+MINISATPROVER_REPO := https://github.com/AlloyTools/minisatprover+MINISATPROVER_COMMIT := 54bf0f5d07024a7b91052c8371de75accc70c4a9+ifeq ($(shell uname -s),Darwin)+ MINISATPROVER := lib/libminisatprover.dylib else- UNAME := $(shell uname -s)- ifeq ($(UNAME), Linux)- MNAME := $(shell uname -m | tr "A-Z" "a-z")- ifeq ($(MNAME), i686)- LIB := x86-linux/libminisatprover*- endif- ifeq ($(MNAME), x86_64)- # amd64 is a nickname for x86_64- LIB := amd64-linux/libminisatprover*- endif- endif- ifeq ($(UNAME),Darwin)- WGET_COMMAND := curl -O- LIB := x86-mac/libminisatprover*- endif+ MINISATPROVER := lib/libminisatprover.so+ # CMake looks for the JNI headers in JAVA_HOME, which Linux distributions often leave unset.+ JAVA_HOME ?= $(shell dirname $$(dirname $$(readlink -f $$(command -v javac)))) endif # Calling `make` should only build-all: alloyIG.jar lib build+all: alloyIG.jar $(MINISATPROVER) build # Calling `make install to=<target directory>` should only install install: mkdir -p $(to)+ cp -f $(ALLOY_JAR) $(to) mkdir -p $(to)/lib- cp -f lib/*minisatprover* $(to)/lib- cp -f alloy4.2.jar $(to)+ cp -f $(MINISATPROVER) $(to)/lib cp -f alloyIG.jar $(to) cp -f LICENSE $(to)/ cp -f CHANGES.md $(to)/claferIG-CHANGES.md@@ -40,35 +34,40 @@ # Build takes less time. For ease of development. build: alloyIG.jar stack build+ cp alloyIG.jar `stack path --local-install-root`/bin/+ cp $(ALLOY_JAR) `stack path --local-install-root`/bin/+ if test -f $(MINISATPROVER); then cp -R lib `stack path --local-install-root`/bin/; fi -alloyIG.jar: alloy4.2.jar src/manifest src/org/clafer/ig/AlloyIG.java src/manifest src/org/clafer/ig/Util.java src/org/clafer/ig/AlloyIGException.java src/edu/mit/csail/sdg/alloy4compiler/parser/AlloyCompiler.java+alloyIG.jar: $(ALLOY_JAR) src/manifest src/org/clafer/ig/AlloyIG.java src/org/clafer/ig/Util.java src/org/clafer/ig/AlloyIGException.java src/org/alloytools/solvers/natv/minisatprover/FixedMiniSatProver.java mkdir -p dist/javabuild- javac -cp "alloy4.2.jar" -d dist/javabuild src/org/clafer/ig/AlloyIG.java src/org/clafer/ig/Util.java src/org/clafer/ig/AlloyIGException.java src/edu/mit/csail/sdg/alloy4compiler/parser/AlloyCompiler.java- jar cfm alloyIG.jar src/manifest -C dist/javabuild org/clafer/ig/ -C dist/javabuild edu+ javac --release 17 -cp "$(ALLOY_JAR)" -d dist/javabuild src/org/clafer/ig/AlloyIG.java src/org/clafer/ig/Util.java src/org/clafer/ig/AlloyIGException.java src/org/alloytools/solvers/natv/minisatprover/FixedMiniSatProver.java+ jar cfm alloyIG.jar src/manifest -C dist/javabuild org/clafer/ig/ -C dist/javabuild org/alloytools/ -.PHONY : test lib+$(MINISATPROVER): native/minisatprover/CMakeLists.txt native/minisatprover/MiniSatProver.cpp native/minisatprover/AlloyMiniSatProver.h+ rm -rf native/minisatprover/repo dist/minisatprover+ git clone -q $(MINISATPROVER_REPO) native/minisatprover/repo+ git -C native/minisatprover/repo checkout -q $(MINISATPROVER_COMMIT)+ cmake -S native/minisatprover -B dist/minisatprover $(if $(JAVA_HOME),-DJAVA_HOME=$(JAVA_HOME))+ cmake --build dist/minisatprover+ mkdir -p lib+ cp dist/minisatprover/$(notdir $(MINISATPROVER)) $@ -lib: alloy4.2.jar- @if test -z $(LIB); then \- echo "[WARNING] Did not find a minisat prover binary suitable for your system. You may need to build the binary yourself."; \- else \- unzip alloy4.2.jar $(LIB) -d lib; \- chmod +x lib/$(LIB); \- cp lib/$(LIB) lib; \- fi+.PHONY : test test:- cp alloyIG.jar `stack path --dist-dir`/build/test-suite/- cp alloy4.2.jar `stack path --dist-dir`/build/test-suite/- cp -R lib `stack path --dist-dir`/build/test-suite/+ stack test --no-run-tests + cp alloyIG.jar `stack path --dist-dir`/build/model-tests/+ cp $(ALLOY_JAR) `stack path --dist-dir`/build/model-tests/+ if test -f $(MINISATPROVER); then cp -R lib `stack path --dist-dir`/build/model-tests/; fi cp alloyIG.jar `stack path --dist-dir`/build/claferIG/- cp alloy4.2.jar `stack path --dist-dir`/build/claferIG/- cp -R lib `stack path --dist-dir`/build/claferIG/+ cp $(ALLOY_JAR) `stack path --dist-dir`/build/claferIG/+ if test -f $(MINISATPROVER); then cp -R lib `stack path --dist-dir`/build/claferIG/; fi stack test clean: stack clean rm -f alloyIG.jar+ rm -rf lib native/minisatprover/repo dist/minisatprover rm -rf tools tags:@@ -78,21 +77,6 @@ codex update mv codex.tags tags -WGET_COMMAND := wget-ifeq ($(OS),Windows_NT)- ifeq ($(shell which wget), which: wget: unkown command)- pacman -S make wget- endif-else- UNAME_S := $(shell uname -s)- ifeq ($(UNAME_S),Darwin)- WGET_COMMAND := curl -O- endif-endif--alloy4.2.jar:- @if test ! -f "alloy4.2.jar"; then \- echo "[WARNING] Missing alloy4.2.jar. Downloading..."; \- $(WGET_COMMAND) http://alloy.mit.edu/alloy/downloads/alloy4.2_2015-02-22.jar; \- mv alloy4.2_2015-02-22.jar alloy4.2.jar; \- fi+$(ALLOY_JAR):+ @echo "[WARNING] Missing $(ALLOY_JAR). Downloading..."+ curl -fsSL -o $(ALLOY_JAR) $(ALLOY_URL)
README.md view
@@ -1,6 +1,6 @@ # Clafer Instance Generator -##### v0.4.5+##### v0.5.8 [Clafer](http://clafer.org) is a powerful (equivalent to first-order predicate logic) yet lightweight structural modeling language. Despite simplicity and conciseness of Clafer, writing correct models remains challenging due to hard-to-predict interactions among all constraints expressed in the model. @@ -10,79 +10,75 @@ ## Contributors -* [Michał Antkiewicz](http://gsd.uwaterloo.ca/mantkiew), Main developer.+* [Michał Antkiewicz](https://uwaterloo.ca/wise-lab/profiles/michal-antkiewicz), Main developer. * [Jimmy Liang](http://gsd.uwaterloo.ca/jliang), Original developer. * Luke Michael Brown, co-op student May-Aug 2013. Many improvements. ## Getting the Clafer Instance Generator -Clafer can be installed from a binary distribution (preferred), from Hackage, and from the source code.+ClaferIG can be installed from a binary distribution (preferred), from Hackage, and from the source code. ### Dependencies for running Regardless of the installation method, the following are required: -* [Clafer](https://github.com/gsdlab/clafer) v0.4.5-* [Java Platform (JDK)](http://www.oracle.com/technetwork/java/javase/downloads/index.html) v8+, 64bit- * On Windows, Java must be 32bit because of Alloy, 64bit otherwise-* [Alloy4.2](http://alloy.mit.edu/alloy/download.html)--### Installation from binaries+* [Java](https://adoptium.net) 17 or newer, 64-bit (a runtime is enough)+* `alloyIG.jar` (in this repository) and [Alloy 6.2.0](https://github.com/AlloyTools/org.alloytools.alloy/releases/tag/v6.2.0) (`alloy6.2.0.jar`), in the directory of the `claferIG` executable+ * Alloy includes the MiniSat solver with UnSAT cores for Linux and macOS; on Windows, ClaferIG generates instances but cannot compute UnSAT cores and near-miss instances+ * the MiniSat build in Alloy 6.2.0 is several times slower than the one in Alloy 4.2 because it is compiled without optimization ([AlloyTools/org.alloytools.alloy#352](https://github.com/AlloyTools/org.alloytools.alloy/issues/352)); ClaferIG uses `lib/libminisatprover.so` (`.dylib` on macOS) in the directory of its executable instead, if present. `make` builds it from source. -Binary distributions of the release 0.4.5 of Clafer Tools for Windows, Mac, and Linux,-can be downloaded from [Clafer Tools - Binary Distributions](http://gsd.uwaterloo.ca/clafer-tools-binary-distributions).+The Clafer compiler is part of `claferIG`: the executable `clafer` is not needed. -1. download the binaries and unpack `<target directory>` of your choice,-2. add the `<target directory>` to your system path so that the executables can be found.+ClaferIG looks for the jars and `lib/` in the directory of its executable, after following symbolic links: put them next to the file itself, not next to a link to it. -### Installation From Hackage+### Installation from binaries -Clafer is now available on [Hackage](http://hackage.haskell.org/package/claferIG-0.4.5/) and it can be installed using either [`stack`](https://github.com/commercialhaskell/stack) or [`cabal-install`](https://hackage.haskell.org/package/cabal-install).+Binary distributions of Clafer Tools (`clafer`, `claferIG`, and `chocosolver` with the jars they need; Linux x86-64 for the recent releases)+can be downloaded from [Clafer Tools - Binary Distributions](https://wiselab.uwaterloo.ca/clafer-tools-binary-distributions/).+They include `alloyIG.jar`, `alloy6.2.0.jar`, and the optimized `lib/libminisatprover.so`. -#### Installation using `stack`+1. Download the binaries and unpack them into a `<target directory>` of your choice.+2. Add the `<target directory>` to your system path so that the executables can be found. -Stack is the only requirement: no other Haskell tooling needs to be installed because stack will automatically install the needed Haskell build tools.+### Installation from Hackage -1. [install `stack`](https://github.com/commercialhaskell/stack#how-to-install)-2. Execute- * `stack install claferIG`- * ``` cd `stack --local-bin-path` ```- * `wget http://alloy.mit.edu/alloy/downloads/alloy4.2_2015-02-22.jar`- * `mv alloy4.2_2015-02-22.jar alloy4.2.jar`- * `wget https://github.com/gsdlab/claferIG/raw/master/alloyIG.jar`- * `mkdir lib`- * `cd lib`- * Depending on your OS:- * for Win, `stack exec wget -- https://github.com/gsdlab/claferIG/raw/master/lib/libminisatprover.dll`- * for Linux, `wget https://github.com/gsdlab/claferIG/raw/master/lib/libminisatprover.so`- * for Mac, `wget https://github.com/gsdlab/claferIG/raw/master/lib/libminisatprover.dylib`+ClaferIG is available on [Hackage](https://hackage.haskell.org/package/claferIG) and it can be installed using either [`cabal-install`](https://hackage.haskell.org/package/cabal-install) or [`stack`](https://haskellstack.org).+Either way, the jars are installed separately, into the directory of the executable. #### Installation using `cabal-install` Dependencies -* [GHC](https://www.haskell.org/downloads) >= 7.10.3 and 8.0.1 are recommended,-* `cabal-install` >= 1.18, should be installed together with a GHC distribution,+* `ghc-9.6.7` or `ghc-9.12.4`+* `cabal-install-3.10.3` or newer -1. Install GHC+1. Use [`ghcup`](https://www.haskell.org/ghcup/) to install `ghc` and `cabal` 2. `cabal update`-3. `cabal install claferIG`-4. `cd <cabal's lib or share folder>` (`C:\Users\<user>\AppData\Roaming\cabal\x86_64-windows-ghc-8.0.1\claferIG-0.4.5` on Windows or `.cabal/share/x86_64-linux-ghc-8.0.1/claferIG-0.4.5/` on Linux)-5. to automatically download alloy4.2.jar- * execute `make alloy4.2.jar`-7. copy the following into the Cabal's `bin` folder- * the file `alloyIG.jar`- * the file `alloy4.2.jar`- * the folder `lib`+3. `cabal install claferIG --install-method=copy --installdir=<target directory>`+4. In the `<target directory>`, execute+ * `curl -fsSL -o alloy6.2.0.jar https://github.com/AlloyTools/org.alloytools.alloy/releases/download/v6.2.0/org.alloytools.alloy.dist.jar`+ * `curl -fsSL -O https://github.com/gsdlab/claferIG/raw/master/alloyIG.jar`+5. Add the `<target directory>` to your system path. +`--install-method=copy` is needed: by default, `cabal install` puts a symbolic link into its `bin` directory, and ClaferIG would look for the jars in cabal's package store, where the link points.++#### Installation using `stack`++ClaferIG is not part of Stackage snapshots, so give the versions of both packages; their dependencies come from the snapshot.+This release is tested with the snapshot `nightly-2026-11-11`:++1. [Install `stack`](https://docs.haskellstack.org/en/stable/install_and_upgrade/)+2. `stack install claferIG-0.5.8 clafer-0.5.8 --resolver nightly-2026-11-11`+3. In `~/.local/bin` (``stack path --local-bin``), where the executable is copied, download the jars as in step 4 above.+ ### Installation from the source code Dependencies -* [GHC](https://www.haskell.org/downloads) >= v7.10.3-* [Clafer compiler](https://github.com/gsdlab/clafer) (to produce Alloy models (`.als`)).-* On Linux, might need to manually install `zlib1g-dev` and `libncurses5-dev` to build one of Haskell packages on which ClaferIG depends- * on Ubuntu, execute `sudo apt-get install zlib1g-dev libncurses5-dev`+* [`stack`](https://haskellstack.org)+* the source code of the [Clafer compiler](https://github.com/gsdlab/clafer) in a sibling directory `clafer` (`stack.yaml` builds it from `../clafer`)+* On Linux, the development files of `gmp`, `ncurses` and `zlib`, needed to build ClaferIG and its dependencies+ * on Ubuntu, execute `sudo apt install libgmp-dev libncurses-dev zlib1g-dev` On Windows @@ -91,7 +87,7 @@ * update MSYS2 packages * follow [III. Updating packages](http://sourceforge.net/p/msys2/wiki/MSYS2%20installation/) but always execute `stack exec pacman -- <arguments for pacman>` * execute- * `stack exec pacman -- -S make wget unzip diffutils`+ * `stack exec pacman -- -S make diffutils` ### Important: branches must correspond @@ -103,29 +99,26 @@ ### Building -1. install the [Clafer compiler](https://github.com/gsdlab/clafer)-2. in some `<source directory>`, execute `git clone git://github.com/gsdlab/claferIG.git`+1. in some `<source directory>`, execute `git clone https://github.com/gsdlab/clafer.git` (check out the same branch as ClaferIG)+2. in the same `<source directory>`, execute `git clone https://github.com/gsdlab/claferIG.git` 3. in `<source directory>/claferIG`, execute `stack setup`. This will install all dependencies, build tools, and MSYS2 (on Windows). 4. `cd <source directory>/claferIG` * `make`+ * this also builds the optimized MiniSat solver with UnSAT cores in `lib/`, which needs `git`, `cmake`, a C++ compiler and a JDK ### Installation 1. execute `make install to=<target directory>` #### Note:-> On Windows, use `/` with the `make` command instead of `\`, e.g., `make install to=/c/clafer-tools-0.4.5/`---## Integration with Sublime Text 2/3+> On Windows, use `/` with the `make` command instead of `\`, e.g., `make install to=/c/clafer-tools-0.5.4/` -See [ClaferToolsST](https://github.com/gsdlab/ClaferToolsST)--## Integration with VIM-+## Integration with text editors -See [clafer-vim](https://github.com/wasowski/clafer-vim)+* VS Code: [clafer-vscode](https://github.com/gsdlab/clafer-vscode)+* Sublime Text 4: [ClaferToolsST](https://github.com/gsdlab/ClaferToolsST)+* VIM: [clafer-vim](https://github.com/wasowski/clafer-vim) # Usage @@ -136,43 +129,95 @@ (As printed by `claferIG --help`) ```-ClaferIG v0.4.5+ClaferIG 0.5.8 -claferIG [OPTIONS] [FILE]+claferig [OPTIONS] FILE Common flags:- --all=INT Saves all instances up to the- provided scope or a- counterexample.- --savedir=FILE Specify the directory for- storing saved files.- --alloysolution Convert Alloy solution to a- Clafer solution.- -b --bitwidth=INTEGER Set the bitwidth for integers.- -m --maxint=INTEGER Set the bitwidth for integers- based on the largest required- number. Overrides --bitwidth- argument.- -u --useuids Use unique clafer names in the- Clafer solution.- --addtypes Add colon/reference types to- the Clafer solution.- -j --json Render solution as JSON- (forces 'addUids').- -i --flatten-inheritance-comp Flatten inheritance during- compiling ('alloy' and 'Alloy'- modes only)- -l --no-layout-comp Don't resolve off-side rule- layout during compiling- -c --check-duplicates-comp Check duplicated clafer names- during compiling- -f --skip-resolver-comp Skip name resolution during- compiling- --ss=SCOPESTRATEGY --scope-strategy-comp Use scope computation strategy- during compiling: none or simple- (default).- -? --help Display help message- -V --version Print version information+ --all[=INTEGER] Saves all instances or+ a counterexample. Reads+ scopes from a+ `.cfr.scope` file or+ uses the provided global+ scope.+ -n=INTEGER Specify the maximum+ number of instances+ saved by --all.+ --savedir=FILE Specify the directory+ for storing saved files.+ --import=FILE Compile the model+ together with the given+ file or URL, which is+ relative to the current+ directory. A model also+ imports files with+ --import in its //#+ OPTIONS directive,+ relative to its own+ folder or URL.+ --import-root=DIR Allow only local+ imports inside DIR,+ after resolving '..' and+ symbolic links (command+ line only). Can be+ repeated.+ --public-imports Allow only URL imports+ from public addresses+ (command line only).+ --import-base=URL The URL from which the+ model's text was read:+ its imports are relative+ to the URL (command line+ only).+ --alloysolution=FILE Convert Alloy solution+ to a Clafer solution.+ -b --bitwidth=INTEGER Set the bitwidth for+ integers.+ -m --maxint=INTEGER Set the bitwidth for+ integers based on the+ largest required number.+ Overrides --bitwidth+ argument.+ -u --useuids Use unique clafer+ names in the Clafer+ solution.+ --addtypes Add colon/reference+ types to the Clafer+ solution.+ -j --json Render solution as+ JSON (forces 'addUids').+ -d --diff Show each next+ instance, or state of a+ trace, as its changes+ from the previous one.+ --dot Render solution as a+ Graphviz graph: for a+ trace, its states and+ transitions.+ --tl=INTEGER Set the maximum length+ of the traces of a+ dynamic model (default:+ 10).+ -i --flatten-inheritance-comp Flatten inheritance+ during compiling+ ('alloy' mode only)+ -l --no-layout-comp Don't resolve off-side+ rule layout during+ compiling+ -c --check-duplicates-comp Check duplicated+ clafer names during+ compiling+ -f --skip-resolver-comp Skip name resolution+ during compiling+ --ss=SCOPESTRATEGY --scope-strategy-comp Use scope computation+ strategy during+ compiling: none, simple+ (default), or full.+ -? --help Display help message+ -V --version Print version+ information+ --numeric-version Print just the version+ number ``` `claferIG <model file name>.cfr`@@ -183,23 +228,138 @@ - opens a non-interactive session and saves all instances up to the provided scope or a counterexample to files named `<model file name>.cfr.<instance number>.data`, one instance per file. +### Models in several files++A model can import other files, as with the Clafer compiler: `--import=FILE` in the model's `//# OPTIONS` directive, relative to the model's folder, or on the command line, relative to the current directory. The files and their imports are compiled together as one model. A model and its imports can also be URLs (`http://`, `https://`). See [Models in several files](https://github.com/gsdlab/clafer#models-in-several-files) in the compiler's README.++```+//# OPTIONS --import=products.cfr+MyPhone : Phone+```++`claferIG MyPhone.cfr` generates the instances of `MyPhone.cfr` with the clafers of `products.cfr`. The other options of the directives (e.g., `--maxint`, `--no-layout`) apply too, and an error names the file in which it is (`products.cfr:3:11`).++### Dynamic models++A dynamic model, with temporal operators (e.g., `X`, `U`, `initially`) or the temporal modifiers `initial` and `final`, describes how its instances change over time. Its solutions are traces: each `n`ext gives a trace, and the trace is a sequence of states, each an instance of the model. Alloy's traces are lassos: after the last state, the trace loops back to an earlier state, and repeats the states from there forever.++```+//# OPTIONS --import=TrafficLight.cfr+tl : TrafficLight+ [ initially (green --> yellow --> red --> green --> yellow_on --> yellow_off --> off) ]+```++```+=== Trace 1 Begin ===++--- State 0 ---+tl+ on+ normal+ green++--- State 1 ---+tl+ on+ normal+ yellow++...++--- State 6 ---+tl+ off++--- Loop back to state 3 ---++--- Trace 1 End ---+```++`--tl=INTEGER` and the command `tl <number>` set the maximum length of the traces (by default, 10 states). The traces are given from the shortest, and each trace is different from the traces given before, as the states in which the instances are, regardless of the names of their atoms. `--all` saves each trace to its own file, and `--json` gives a trace as `{"states": [...], "loop": 3}`.++Two commands explore other traces than the next one:++* `fork <number>` gives another trace with the same states as the last trace before the state `<number>`: what else can happen from there. E.g., `fork 2` keeps the states 0 and 1.+* `config` gives a trace with another configuration: the clafers that do not change over time, e.g., the features of a product line declared `final`, differ from those of the traces given so far.++`config` also works on static models, whose next instances often differ only in a value: it gives an instance whose structure, its clafers without the values of their references, differs from those of the instances given so far. Each `config` gives, e.g., another selection of features of a product line. The next instances then continue from it, without the structures given so far.++The command `check` checks the assertions of the model, also the nested ones and those of temporal models, one by one. An assertion holds for all the solutions within the scopes and the maximum trace length, so `No counterexample` does not prove it for larger scopes or longer traces. A counterexample is shown like any other solution, and the next solution of the model stays as it is. Checking a large model can take much longer than generating a solution; lower the maximum trace length (`tl`) to get a faster answer. `check <number>` checks only the assertions on that line, or all of them if the number is not positive.++```+claferIG> check+No counterexample: tl.off => X tl.on (TrafficLight.cfr:13:10)+Counterexample of: never tl.off (TrafficLight.cfr:12:10)+=== Trace 3 Begin ===+...+2 assertion(s) checked within the scopes and the maximum trace length: 1 with a counterexample.+```++The command `dot` saves the most recent solution as a Graphviz graph: a node for each state, with the instance as its label and the name of the state (`S0`, `S1`, ...) outside it, an edge to the next state, and a dashed edge back to the loop state. In the diff view, the first state is in full and each next state shows its changes, which keeps the graph of a large model readable. With `--dot`, solutions are given as such graphs, and `--all` saves them to `.dot` files. To render one:++```bash+dot -Tsvg TrafficLight.cfr.1.dot -o trace.svg+```++A dynamic model, or a scenario, with no traces has an unsat core: the constraints that contradict each other, e.g., a scenario and the transition it does not follow, and a near-miss trace without one of them, as for a static model.++```+ 1) green --> yellow (TrafficLight.cfr:6:33)+ 2) initially (green --> red) (scenario.cfr:3:7)+```++With `--diff`, or after the command `d`, the first state, whose clafers all appear, is shown with `+` on each line, and each next state as its changes from the previous state: the clafers that appear (`+`), with their children, the clafers that disappear (`-`), and the values that change (`~`). Each change is indented as the clafer in the tree, and has the least-partially-qualified name of the clafer, which is qualified only as much as needed to tell it from the other clafers with the same name, e.g., `normal.yellow` if `flashing` also had a `yellow`. An instance has the same name in all the states of a trace, so a clafer that disappears and appears again is the same instance.++```+--- State 0 ---++ tl++ on++ normal++ green++...++--- State 3 ---+- red++ green++--- State 4 ---+- normal++ flashing++ yellow_on+```++In a static model, the diff view shows the first instance with `+` on each line, and each next instance as its differences from the previous instance, by their structure: the names of the instances of different solutions are unrelated, so the numbers of the instances are left out.+ ## Interactive Session Usage In the interactive mode, the users can invoke the following commands by pressing a letter marked in the command name between '' or the whole command as marked by '': ```-ClaferIG v0.4.5+ClaferIG v0.5.8 You can invoke the following commands as indicated by single quotes: [tab] - print the available commands - auto-complete command name, a clafer name, or clafer instance name in a given context-'n'ext, [enter] - to produce the next instance if available or to output a message that no more- instances exist within the given scope+'n'ext, [enter] - to produce the next solution if available, an instance of a static model or a trace+ of a dynamic model, or to output a message that no more solutions exist within+ the given scope 'i'ncrease - to increase the maximum number of instances of a given clafer or all clafers (scope) 's'et - to set the maximum number of instances of a given clafer or all clafers (scope) 'm'axint, 'maxint' - to set the bitwidth by providing the largest integer-sa'v'e - to save all instances displayed so far or a counterexample to files named+'tl' - to set the maximum length of the traces of a dynamic model+'d'iff - to show each next instance or state as its changes from the previous one, or in full+ (+ appears, - disappears, ~ changes its value)+'fork' - to produce another trace with the same first states as the last trace+'config' - to produce a trace of a dynamic model whose clafers that do not change over time+ differ from those of the traces so far, or an instance of a static model whose+ clafers, without the values of their references, differ from those so far+sa'v'e - to save all instances displayed so far or a counterexample to files named <model file name>.cfr.<instance number>.data, one instance per file+'check' - to check the assertions of the model within the scopes and the maximum trace+ length, and to give a counterexample of each one that fails+'dot' - to save the most recent solution as a Graphviz graph, for a trace its states+ and transitions, to <model file name>.cfr.<solution number>.dot 'q'uit - to quit the interactive session 'r'eload - to reload your clafer model 'h'elp - to display this menu options summary@@ -219,6 +379,9 @@ 's <number> [enter]'- to set for the clafers to <number> 's <name> <number>' - to set for the clafer <name> to <number> 'f <name>' - to display a clafer <name>+'tl <number>' - to set the maximum trace length to <number>+'fork <number>' - to produce another trace with the states of the last trace before state <number>+'check <number>' - to check only the assertions on line <number>, or all of them if it is not positive 'setUnsatCoreMinimization fastest' - fastest but the worst 'setUnsatCoreMinimization medium' 'setUnsatCoreMinimization best' - best but slowest even for modest size cores@@ -323,26 +486,15 @@ ## Troubleshooting -If you get an error:--```-Exception in thread "main" java.lang.UnsatisfiedLinkError: no minisatproverx1 in java.library.path- at java.lang.ClassLoader.loadLibrary(Unknown Source)- at java.lang.Runtime.loadLibrary0(Unknown Source)- at java.lang.System.loadLibrary(Unknown Source)- at org.clafer.ig.AlloyIG.main(AlloyIG.java:275)-```--it means that you have a 64bit Java on Windows instead of the required 32bit one.-On Windows, Alloy only supports Minisat with UnSAT core on 32bit Java.-There's nothing we can do.+If ClaferIG reports `No more instances found` for an inconsistent model instead of an UnSAT core,+the MiniSat solver with UnSAT cores is not available on your platform (Windows); see the dependencies above. ## How it works The Clafer instance generator: -* translates the input Clafer model (.cfr) to an Alloy4.2 model (.als). The compiler's intermediate representation (IR) contains the mapping between Clafer names and Alloy names. The IR also contains the scopes for each Alloy signature to ensure that a valid instance can be found if it exists-* invokes Alloy Analyzer to produce an instance or find an UnSAT core+* translates the input Clafer model (.cfr) to an Alloy 6 model (.als). The compiler's intermediate representation (IR) contains the mapping between Clafer names and Alloy names. The IR also contains the scopes for each Alloy signature to ensure that a valid instance can be found if it exists+* invokes Alloy Analyzer with the MiniSat solver with UnSAT cores to produce an instance or find an UnSAT core ** given an UnSAT core, removes constraints from the core until an instance is found - that instance represents the counterexample which violates the removed constraints * translates the instance or the counterexample data produced by Alloy Analyzer to Clafer instance data format using the name map from IR in a reverse direction, * for a counterexample, translates the counter example in Alloy to Claefr instance data and constraint violations in Alloy into constraint violations in Clafer model
alloyIG.jar view
binary file changed (22361 → 31979 bytes)
claferIG.cabal view
@@ -1,77 +1,64 @@-Name: claferIG-Version: 0.4.5+cabal-version: 3.8+name: claferIG+Version: 0.5.8 Synopsis: claferIG is an interactive tool that generates instances of Clafer models. Description: Clafer is a powerful (equivalent to first-order predicate logic) yet lightweight structural modeling language. Despite simplicity and conciseness of Clafer, writing correct models remains challenging due to hard-to-predict interactions among all constraints expressed in the model. Clafer instance generator (ClaferIG) is an interactive tool that generates instances and counter examples of concrete clafers in a Clafer model. If the concrete clafers do not have contradicting constraints, the generator produces valid instance data. Otherwise, the generator produces an unsatisfiable core which included all contradicting constraints and generates a counter example by removing one constraint from the core. The generator can potentially produce many instances if the concrete clafers are not fully specialized. The generator produces different instances on-demand. With these capabilities, the instance generator can be used for debugging models: checking the consistency of the model and detecting under- and overconstraining of the model. The instance generator can also be used programmatically via API (the command line and interactive session interfaces only use the API). Homepage: http://clafer.org License: MIT License-file: LICENSE Author: Jimmy Liang, Michal Antkiewicz, Luke Michael Brown-Maintainer: Michal Antkiewicz <mantkiew@gsd.uwaterloo.ca>+Maintainer: Michal Antkiewicz <michal.antkiewicz@uwaterloo.ca> Stability: Experimental Category: Model Build-type: Simple-Tested-with: GHC == 7.10.3- , GHC == 8.0.1- , GHC == 8.0.2-Cabal-version: >= 1.22+Tested-with: GHC == 9.6.7 || == 9.12.4 data-files: README.md , alloyIG.jar- , CHANGES.md , Makefile- , lib/libminisatprover.dylib- , lib/libminisatprover.so- , lib/minisatprover.dll , stack.yaml+extra-doc-files: CHANGES.md source-repository head type: git- location: git://github.com/gsdlab/claferIG.git-Executable claferIG- build-tools: ghc >= 7.10.3+ location: https://github.com/gsdlab/claferIG.git++flag model-tests+ description: Build the model-tests test suite, which generates instances of the models in+ test/positive with Alloy. The models and alloy6.2.0.jar are not part of the+ package, so it can only be built in a checkout of the repository.+ default: False+ manual: True++common shared-deps default-language: Haskell2010- Main-is: Main.hs- Build-depends: base >= 4.7.0.1 && < 5+ ghc-options: -Wall+ build-depends: base >= 4.18.3.0 && < 5 , containers >= 0.5.5.1 , directory >= 1.2.1.0- , filepath >= 1.3.0.2- , transformers >= 0.3.0.0 - , mtl >= 2.1.3.1-+executable claferIG+ import: shared-deps+ Main-is: Main.hs+ Build-depends: filepath >= 1.3.0.2 , cmdargs >= 0.10.12- , executable-path >= 0.0.3- , haskeline >= 0.7.1.2- , transformers-compat >= 0.3- , mtl-compat >= 0.2.1-- , clafer == 0.4.5- , claferIG == 0.4.5+ , clafer == 0.5.8+ , claferIG == 0.5.8 other-modules: Paths_claferIG+ autogen-modules: Paths_claferIG Hs-Source-Dirs: src-cmd ghc-options: -Wall -fno-warn-orphans library- build-tools: ghc >= 7.10.3- default-language: Haskell2010- build-depends: array >= 0.5.0.0- , base >= 4.7.0.1 && < 5- , containers >= 0.5.5.1- , directory >= 1.2.1.0- , filepath >= 1.3.0.2- , process >= 1.2.0.0- , transformers >= 0.3.0.0-+ import: shared-deps+ build-depends: transformers >= 0.6 , mtl >= 2.1.3.1- , parsec >= 3.1.5-- , data-stringmap >= 1.0.1.1 , executable-path >= 0.0.3- , haskeline >= 0.7.1.2- , json-builder >= 0.3+ , haskeline >= 0.8+ , process >= 1.2.0.0+ , parsec >= 3.1.5+ , exceptions >= 0.10+ , aeson >= 1.1.2.0 , string-conversions >= 0.3.0.3- , transformers-compat >= 0.3- , mtl-compat >= 0.2.1-- , clafer == 0.4.5+ , clafer == 0.5.8 if os(windows) build-depends: HaXml == 1.24@@ -89,28 +76,40 @@ , Language.Clafer.IG.JSONGenerator , Language.Clafer.IG.Process , Language.Clafer.IG.Solution+ , Language.Clafer.IG.SolutionView , Language.Clafer.IG.Sugarer other-modules: Paths_claferIG+ autogen-modules: Paths_claferIG Test-Suite test-suite type: exitcode-stdio-1.0 default-language: Haskell2010 main-is: test-suite.hs hs-source-dirs: test- build-depends: array >= 0.5.0.0- , base >= 4.7.0.1 && < 5+ build-depends: base >= 4.18.3.0 && < 5+ , tasty >= 0.10.1.2+ , tasty-hunit >= 0.9.2+ , tasty-th >= 0.1.3+ , claferIG == 0.5.8+ other-modules: Paths_claferIG+ autogen-modules: Paths_claferIG+ ghc-options: -Wall -fno-warn-orphans++Test-Suite model-tests+ type: exitcode-stdio-1.0+ default-language: Haskell2010+ main-is: model-tests.hs+ hs-source-dirs: test+ if !flag(model-tests)+ buildable: False+ build-depends: base >= 4.18.3.0 && < 5 , directory >= 1.2.1.0+ , containers >= 0.5.5.1 , filepath >= 1.3.0.2- , transformers >= 0.3.0.0-- , HUnit >= 1.2.5.2- , cmdargs >= 0.10.12 , tasty >= 0.10.1.2 , tasty-hunit >= 0.9.2 , tasty-th >= 0.1.3- , transformers-compat >= 0.3-- , clafer == 0.4.5- , claferIG == 0.4.5- other-modules: Paths_claferIG- ghc-options: -Wall -fno-warn-orphans+ , clafer == 0.5.8+ , claferIG == 0.5.8+ -- the tests run in parallel, on 8 cores: with GHC 9.12 and 16 or more, the parallel GC hangs+ ghc-options: -Wall -fno-warn-orphans -threaded -rtsopts "-with-rtsopts=-N8"
− lib/libminisatprover.dylib
binary file changed (74648 → absent bytes)
− lib/libminisatprover.so
binary file changed (75650 → absent bytes)
− lib/minisatprover.dll
binary file changed (142114 → absent bytes)
src-cmd/Main.hs view
@@ -27,12 +27,12 @@ import Language.Clafer.IG.ClaferIG import Language.Clafer.IG.ClaferModel import Language.Clafer.IG.CommandLine+import Language.Clafer.IG.SolutionView import Language.Clafer.IG.Solution import Language.Clafer.IG.Sugarer import Language.Clafer.ClaferArgs import Language.Clafer.JSONMetaData import Language.ClaferT-import Language.Clafer.Common import Control.Monad import Control.Monad.IO.Class import Data.Either@@ -44,18 +44,27 @@ import System.Console.CmdArgs import System.Directory import System.FilePath+import System.IO (hFlush, stdout) claferIGArgsDef :: IGArgs claferIGArgsDef = IGArgs { all = def &= opt "1" &= help "Saves all instances or a counterexample. Reads scopes from a `.cfr.scope` file or uses the provided global scope." &= typ "INTEGER",+ maxInstances = def &= help "Specify the maximum number of instances saved by --all." &= typ "INTEGER" &= explicit &= name "n", saveDir = def &= help "Specify the directory for storing saved files." &= typ "FILE", bitwidth = 4 &= help "Set the bitwidth for integers." &= typ "INTEGER", -- Default bitwidth is 4. maxInt = 7 &= help "Set the bitwidth for integers based on the largest required number. Overrides --bitwidth argument." &= typ "INTEGER",+ import_root_comp = def &= help "Allow only local imports inside DIR, after resolving '..' and symbolic links (command line only). Can be repeated." &= typDir &= explicit &= name "import-root",+ public_imports_comp = def &= help "Allow only URL imports from public addresses (command line only)." &= explicit &= name "public-imports",+ import_base_comp = def &= help "The URL from which the model's text was read: its imports are relative to the URL (command line only)." &= typ "URL" &= explicit &= name "import-base", alloySolution = def &= help "Convert Alloy solution to a Clafer solution." &= typ "FILE", claferModelFile = def &= argPos 0 &= typ "FILE",+ imports_comp = def &= help "Compile the model together with the given file or URL, which is relative to the current directory. A model also imports files with --import in its //# OPTIONS directive, relative to its own folder or URL." &= typFile &= explicit &= name "import", useUids = False &= help "Use unique clafer names in the Clafer solution.", addTypes = False &= help "Add colon/reference types to the Clafer solution.", json = False &= help "Render solution as JSON (forces 'addUids').",+ diff = False &= help "Show each next instance, or state of a trace, as its changes from the previous one.",+ dot = False &= help "Render solution as a Graphviz graph: for a trace, its states and transitions." &= explicit &= name "dot",+ tl_comp = def &= help "Set the maximum length of the traces of a dynamic model (default: 10)." &= typ "INTEGER" &= explicit &= name "tl", flatten_inheritance_comp = def &= help "Flatten inheritance during compiling ('alloy' mode only)" &= name "i", no_layout_comp = def &= help "Don't resolve off-side rule layout during compiling" &= name "l", check_duplicates_comp = def &= help "Check duplicated clafer names during compiling" &= name "c",@@ -94,14 +103,17 @@ Left l -> do mapM_ putStrLn $ printError l putStrLn "Press enter to retry."+ -- a tool reading the output through a pipe, e.g., ClaferIDE, gets the error+ -- only when it is flushed+ hFlush stdout void getLine tryClaferIG args3 runClaferIG :: IGArgs -> IO (Either ClaferErrs ()) runClaferIG args' = runClaferIGT args' $ do- let claferModelFileName = claferModelFile args'- cModel <- liftIO $ strictReadFile claferModelFileName+ claferModelFileName <- getModelFileName+ cModel <- getClaferModel if null cModel then error "Cannot instantiate an empty model." else liftIO $ putStrLn "Compiling the Clafer model..."@@ -127,7 +139,8 @@ (globalScopes, normalScopes) = partition (\(uid, _) -> null uid) uidScopes -- from the globalScopes, take the maximum globalScopeVals = map snd globalScopes- globalScope = maximum globalScopeVals+ -- a file may list only some clafers, without the global scope+ globalScope = if null globalScopeVals then scope else maximum globalScopeVals -- add the "this/" prefix normalScopesAlloy = map (\(uid, scope2) -> ("this/"++uid, scope2)) normalScopes setGlobalScope globalScope@@ -139,7 +152,8 @@ counterRef <- liftIO $ newIORef 1 let saveDirectory = fromMaybe return $ underDirectory `liftM` saveDir args'- saveAll (savePath claferModelFileName counterRef >>= saveDirectory)+ let extension = if dot args' && not (json args') then ".dot" else ".data"+ saveAll (maxInstances args') (savePath extension claferModelFileName counterRef >>= saveDirectory) quit Nothing -> do liftIO $ putStrLn "Type 'h' for the list of available REPL commands\n"@@ -150,26 +164,30 @@ runAlloySolution :: IGArgs -> IO (Either ClaferErrs ()) runAlloySolution args' = runClaferIGT args' $ do- let claferModelFileName = claferModelFile args'- cModel <- liftIO $ strictReadFile claferModelFileName+ cModel <- getClaferModel when (cModel == "") $ error $ "Cannot convert Alloy solution without the Clafer model from which the instance was created.\n" ++ "Usage: claferIG [OPTIONS] <model.cfr> --alloy-solution=<instance.xml>\n" alloyInstance <- liftIO $ strictReadFile $ alloySolution args' -- It's an Alloy XML file in this case when (null alloyInstance) $ error $ "Provide an Alloy solution Alloy file name.\n" ++ "Usage: claferIG [OPTIONS] <model.cfr> --alloy-solution=<instance.xml>\n"- env <- getClaferEnv- let (_, genv', _) = fromJust $ cIr env+ dynamic <- isDynamicModel+ -- the clafers by their Alloy names, as in the Alloy solution+ uidIClaferMap' <- getUIDIClaferMap+ toUid <- getToUid let sMap = Map.empty- uidIClaferMap' = uidClaferMap genv'- liftIO $ putStrLn $ show $ (sugarClaferModel (useUids args') (addTypes args') uidIClaferMap' $ buildClaferModel $ parseSolution alloyInstance) $ sMap+ -- the trace of a dynamic model+ (states, loopState) = parseTrace alloyInstance+ liftIO $ putStrLn $ if dynamic+ then solutionText $ ClaferTrace (sugarClaferStates toUid (useUids args') (addTypes args') uidIClaferMap' (map buildStateModel states) sMap) loopState+ else show $ (sugarClaferModel toUid (useUids args') (addTypes args') uidIClaferMap' $ buildClaferModel $ parseSolution alloyInstance) $ sMap -savePath :: FilePath -> IORef Int -> IO FilePath-savePath file' counterRef =+savePath :: String -> FilePath -> IORef Int -> IO FilePath+savePath extension file' counterRef = do counter <- readIORef counterRef writeIORef counterRef (counter + 1)- return $ file' ++ "." ++ (show counter) ++ ".data"+ return $ file' ++ "." ++ (show counter) ++ extension underDirectory :: FilePath -> FilePath -> IO FilePath@@ -179,14 +197,23 @@ return $ joinPath [dir, file'] -saveAll :: IO FilePath -> ClaferIGT IO ()-saveAll nextFile =+-- | Saves the instances, or the traces of a dynamic model, at most the given number of them, if any+saveAll :: Maybe Integer -> IO FilePath -> ClaferIGT IO ()+saveAll (Just remaining) _ | remaining <= 0 = return ()+saveAll maxInstances' nextFile = do file' <- liftIO nextFile liftIO $ createDirectoryIfMissing True $ takeDirectory file' solution <- next+ claferIGArgs' <- getClaferIGArgs+ uidIClaferMap' <- getUIDIClaferMap case solution of- Instance{modelInstance = modelInstance'} -> do- liftIO $ writeFile file' (show modelInstance')- saveAll nextFile+ Instance{modelSolution = modelSolution'} -> do+ let output' = if json claferIGArgs'+ then solutionJSON uidIClaferMap' modelSolution'+ else if dot claferIGArgs'+ then solutionDot modelSolution'+ else solutionText modelSolution'+ liftIO $ writeFile file' output'+ saveAll (subtract 1 <$> maxInstances') nextFile _ -> return ()
src/Language/Clafer/IG/AlloyIGInterface.hs view
@@ -26,6 +26,7 @@ import Control.Applicative import Control.Monad+import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Reader import Control.Monad.Trans.State.Strict@@ -33,18 +34,20 @@ import Data.Maybe import Language.Clafer.Front.AbsClafer (Span(..), Pos(..)) import Language.Clafer.IG.Process-import System.Console.Haskeline.MonadException import Prelude+import System.Directory (createDirectory, doesFileExist, getTemporaryDirectory, removeFile)+import System.Environment (getEnvironment)+import System.IO (hClose, openTempFile)+import System.Info (os) -- | An interface to the Alloy Analyzer -newtype AlloyIGT m a = AlloyIGT (StateT (Maybe AlloyIGEnv) (ReaderT Process m) a) deriving (Applicative, Functor, Monad, MonadIO)+-- | The process of alloyIG and the folder of its temporary files+newtype AlloyIGT m a = AlloyIGT (StateT (Maybe AlloyIGEnv) (ReaderT (Process, FilePath) m) a) deriving (Applicative, Functor, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask) instance MonadTrans AlloyIGT where lift = AlloyIGT . lift . lift -deriving instance MonadException m => MonadException (AlloyIGT m)- fetch :: Monad m => AlloyIGT m AlloyIGEnv fetch = fromMaybe (error "AlloyIG not loaded.") `liftM` AlloyIGT get @@ -55,8 +58,12 @@ set = AlloyIGT . put . Just proc :: Monad m => AlloyIGT m Process-proc = AlloyIGT ask+proc = AlloyIGT $ asks fst +-- | The folder of the temporary files of the session, which alloyIG removes when it exits+sessionTmpdir :: Monad m => AlloyIGT m FilePath+sessionTmpdir = AlloyIGT $ asks snd+ -- | Instance generator's environment data AlloyIGEnv = AlloyIGEnv {alloyModel::String, sigMap::Map String Sig, scopes::Map String Integer, globalScope::Integer} @@ -67,7 +74,7 @@ data Multiplicity = One | Lone | Some | Any deriving (Eq, Read, Show) -data UnsatCore = UnsatCore{core::[Span]} deriving Show+newtype UnsatCore = UnsatCore{core::[Span]} deriving Show @@ -82,13 +89,35 @@ runAlloyIGT run = do execPath <- liftIO $ executableDirectory- proce <- liftIO $ pipeProcess "java" ["-Djava.library.path=" ++ execPath ++ "lib" , "-jar", execPath ++ "alloyIG.jar"]+ -- The minisat prover built with optimization, if it is installed next to claferIG;+ -- otherwise Alloy uses its own build, which is much slower.+ let prover = execPath ++ "lib/" ++ (if os == "darwin" then "libminisatprover.dylib" else "libminisatprover.so")+ hasProver <- liftIO $ doesFileExist prover+ let proverArg = ["-Dalloy.native.lib.minisatprover=" ++ prover | hasProver]+ tmpdir <- liftIO newSessionTmpdir+ environment <- liftIO getEnvironment+ let tmpdirArgs = ["-Djava.io.tmpdir=" ++ tmpdir, "-Dclafer.ig.sessionTmpdir=true"]+ proce <- liftIO $ pipeProcess "java" (["--enable-native-access=ALL-UNNAMED"] ++ proverArg ++ tmpdirArgs ++ ["-jar", execPath ++ "alloyIG.jar"])+ (("TMPDIR", tmpdir) : Prelude.filter ((/= "TMPDIR") . fst) environment) - runReaderT (evalStateT (unwrap run) Nothing) proce+ runReaderT (evalStateT (unwrap run) Nothing) (proce, tmpdir) where unwrap (AlloyIGT a) = a +-- | A new folder for the temporary files of Alloy, which alloyIG removes when it exits.+newSessionTmpdir :: IO FilePath+newSessionTmpdir =+ do+ tmp <- getTemporaryDirectory+ (name, handle) <- openTempFile tmp "claferIG"+ hClose handle+ let tmpdir = name ++ ".d"+ createDirectory tmpdir+ removeFile name+ return tmpdir++ getAlloyModel :: MonadIO m => AlloyIGT m String getAlloyModel = fetches alloyModel @@ -149,6 +178,18 @@ False -> return Nothing +-- | Check an assertion in alloyIG: its counterexample, if any+sendCheckCommand :: MonadIO m => String -> AlloyIGT m (Maybe String)+sendCheckCommand assertion =+ do+ putMsg "check"+ putMsg assertion+ status <- readMsg+ case status of+ True -> Just `liftM` getMsg+ False -> return Nothing++ getScope :: MonadIO m => String -> AlloyIGT m Integer getScope sig = do@@ -257,9 +298,43 @@ sendSetBitwidthCommand :: MonadIO m => Integer -> AlloyIGT m () sendSetBitwidthCommand bitwidth = do- when (bitwidth < 0) $ fail (show bitwidth ++ " is not a valid bitwidth.")+ when (bitwidth < 0) $ error (show bitwidth ++ " is not a valid bitwidth.") putMsg "setBitwidth" putMsg $ show bitwidth+++-- | Get a trace of a dynamic model with the same states as the trace given last before the given+-- state, which differs from the traces given so far+sendForkCommand :: MonadIO m => Integer -> AlloyIGT m (Maybe String)+sendForkCommand state =+ do+ putMsg "fork"+ putMsg $ show state+ status <- readMsg+ case status of+ True -> Just `liftM` getMsg+ False -> return Nothing+++-- | Get a trace of a dynamic model whose relations that do not change over time differ from those+-- of the traces given so far+sendNextConfigurationCommand :: MonadIO m => AlloyIGT m (Maybe String)+sendNextConfigurationCommand =+ do+ putMsg "nextConfiguration"+ status <- readMsg+ case status of+ True -> Just `liftM` getMsg+ False -> return Nothing+++-- | Tell alloyIG to change the maximum length of the traces of a dynamic model+sendSetMaxTraceLengthCommand :: MonadIO m => Integer -> AlloyIGT m ()+sendSetMaxTraceLengthCommand traceLength =+ do+ when (traceLength < 1) $ error (show traceLength ++ " is not a valid trace length.")+ putMsg "setMaxTraceLength"+ putMsg $ show traceLength -- | Tell alloyIG to quit
src/Language/Clafer/IG/ClaferIG.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE NamedFieldPuns, GeneralizedNewtypeDeriving, StandaloneDeriving, DeriveDataTypeable #-}+{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} {- Copyright (C) 2012-2017 Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>@@ -30,6 +30,8 @@ getClaferIGArgs, getConstraints, getClaferModel,+ getModelFiles,+ getModelFileName, getStrMap, getUIDIClaferMap, ClaferIGT(..),@@ -37,6 +39,7 @@ Counterexample(..), runClaferIGT, getAlloyModel,+ getSessionTmpdir, solve, getClafers, getGlobalScope,@@ -49,7 +52,14 @@ increaseScope, setScope, setAlloyScope,+ hasNoInstances, next,+ getAssertions,+ checkAssertion,+ isDynamicModel,+ setMaxTraceLength,+ fork,+ nextConfiguration, setUnsatCoreMinimization, setBitwidth, quit,@@ -58,13 +68,20 @@ fst3, getlineNumMap, strictReadFile,- sigToClaferName) where+ sigToClaferName,+ claferNameOfSig,+ sigOfUID,+ uidOfSig,+ getToUid) where import Language.Clafer import Language.Clafer.Common+import Language.Clafer.Generator.AlloyNames (alloyNames, toAlloyNames, fromAlloyName)+import Language.Clafer.Import (ModelFile, readModel, modelText, modelPosition) import Language.Clafer.QNameUID import Language.ClaferT import Language.Clafer.Intermediate.Intclafer+import Language.Clafer.Intermediate.ScopeAnalysis (emptyAbstracts) import Language.Clafer.IG.AlloyIGInterface (AlloyIGT) import qualified Language.Clafer.IG.AlloyIGInterface as AlloyIG import Language.Clafer.IG.ClaferModel@@ -73,16 +90,19 @@ import Language.Clafer.IG.Sugarer import Control.Applicative import Control.Monad+import Control.Monad.Catch import Control.Monad.Except+import Control.Monad.IO.Class+import Control.Monad.Trans import Control.Monad.Trans.State.Strict import Data.List import Data.Monoid import Data.Tuple (swap) import Data.Map as Map hiding (map, null) import qualified Data.Sequence as Seq+import qualified Data.Set as Set import Data.Maybe import Data.Data-import System.Console.Haskeline.MonadException import Paths_claferIG (version) import Data.Version (showVersion) import Prelude@@ -92,14 +112,22 @@ data IGArgs = IGArgs { all :: Maybe Integer,+ maxInstances :: Maybe Integer, saveDir :: Maybe FilePath, claferModelFile :: FilePath,+ imports_comp :: [FilePath],+ import_root_comp :: [FilePath],+ public_imports_comp :: Bool,+ import_base_comp :: String, alloySolution :: FilePath, bitwidth :: Integer, maxInt :: Integer, useUids :: Bool, addTypes :: Bool, json :: Bool,+ diff :: Bool,+ dot :: Bool,+ tl_comp :: Maybe Integer, flatten_inheritance_comp :: Bool, no_layout_comp :: Bool, check_duplicates_comp :: Bool,@@ -109,9 +137,7 @@ } deriving (Show, Data, Typeable) newtype ClaferIGT m a = ClaferIGT (StateT ClaferIGEnv (AlloyIGT m) a)- deriving (Applicative, Functor, Monad, MonadIO)--deriving instance MonadException m => MonadException (ClaferIGT m)+ deriving (Applicative, Functor, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask) instance MonadTrans ClaferIGT where lift = ClaferIGT . lift . lift@@ -129,9 +155,9 @@ set = ClaferIGT . put runClaferIGT :: MonadIO m => IGArgs -> ClaferIGT m a -> m (Either ClaferErrs a)-runClaferIGT args run =+runClaferIGT igArgs run = AlloyIG.runAlloyIGT $ runExceptT $ do- env <- (ExceptT $ load args) `catchError` (\x -> lift AlloyIG.sendQuitCommand >> throwError x)+ env <- ExceptT (load igArgs) `catchError` (\x -> lift AlloyIG.sendQuitCommand >> throwError x) lift $ evalStateT (unwrap run) env where unwrap (ClaferIGT c) = c@@ -142,19 +168,29 @@ claferIGArgs :: IGArgs, constraints:: [Constraint], claferModel:: String,+ modelFiles :: [ModelFile],+ modelFileName :: FilePath, qNameMaps :: QNameMaps, info :: UIDIClaferMap, strMap :: Map Int String,- lineNumMap :: Map Integer String+ lineNumMap :: Map Integer String,+ -- | A dynamic model, with temporal operators or modifiers, whose solutions are traces+ dynamicModel :: Bool,+ -- | The sigs of the abstract clafers that no concrete clafer inherits from: their scopes stay 0+ emptySigs :: Set.Set String,+ -- | The Alloy names of the clafers whose UIDs cannot be Alloy names, e.g., sig_1 for sig, by+ -- UID. claferIG works with the clafers by their Alloy names (the IR with them, its map,+ -- the sigs); the UIDs are used for the names that the user gives and the scope files.+ alloyNameMap :: Map UID String } data Instance =- Instance {modelInstance::ClaferModel, alloyModelInstance::String} |+ Instance {modelSolution::ClaferSolution, alloyModelInstance::String} | UnsatCore {unsatConstraints::[Constraint], counterexample::Maybe Counterexample} | NoInstance -data Counterexample = Counterexample {removedConstraints::[Constraint], counterexampleInstance::ClaferModel, counterexampleAlloyInstance::String}+data Counterexample = Counterexample {removedConstraints::[Constraint], counterexampleInstance::ClaferSolution, counterexampleAlloyInstance::String} getClaferEnv :: Monad m => ClaferIGT m ClaferEnv getClaferEnv = fetches claferEnv'@@ -171,35 +207,53 @@ getClaferModel :: Monad m => ClaferIGT m String getClaferModel = fetches claferModel +-- | The files of the model: the imported files, then the model.+getModelFiles :: Monad m => ClaferIGT m [ModelFile]+getModelFiles = fetches modelFiles++-- | The name of the model's file, which names the saved files: for a model read from a URL,+-- the last segment of the URL.+getModelFileName :: Monad m => ClaferIGT m FilePath+getModelFileName = fetches modelFileName+ getStrMap :: Monad m => ClaferIGT m (Map Int String) getStrMap = fetches strMap load :: MonadIO m => IGArgs -> AlloyIGT m (Either ClaferErrs ClaferIGEnv) load igArgs = runExceptT $ do- claferModel <- liftIO $ strictReadFile claferFile'+ when (null claferFile') $ throwError $ inFiles [] $ ClaferErrs [ClaferErr "Provide the file name or URL of a Clafer model."]+ -- the model, the files it imports, and the options of all of them+ (claferArgs', modelFiles') <- ExceptT $ liftIO $ either (Left . inFiles [] . ClaferErrs . (:[]) . ClaferErr) Right <$> readModel claferArgs+ let claferModel = modelText modelFiles'+ -- the integer range of the options (--maxint, --minint) raises the bitwidth+ bitwidth' = maximum $ bitwidth igArgs : map requiredBitwidth (catMaybes [maxint claferArgs', (\n -> -n - 1) <$> minint claferArgs']) - (claferEnv', alloyModel, mapping, sMap) <- ExceptT $ return $ callClaferTranslator claferModel+ (claferEnv', alloyModel, mapping, sMap, dynamic) <- ExceptT $ return $ mapLeft (inFiles modelFiles') $ callClaferTranslator claferArgs' claferModel let- (ir, genv', _) = fromJust $ cIr claferEnv'- let constraints = parseConstraints claferModel ir mapping+ (ir0, genv', _) = fromJust $ cIr claferEnv'+ -- the clafers by their Alloy names, as in the Alloy model+ names = alloyNames ir0+ ir = toAlloyNames names ir0+ let constraints = parseConstraints modelFiles' ir mapping lift $ AlloyIG.sendLoadCommand alloyModel lift $ AlloyIG.sendSetBitwidthCommand bitwidth' - let qNameMaps = deriveQNameMaps ir+ let qNameMaps = deriveQNameMaps ir0 - let uidIClaferMap' = uidClaferMap genv'- let irTrace = editMap $ irModuleTrace claferEnv'+ let uidIClaferMap' = if null names then uidClaferMap genv' else createUidIClaferMap ir+ let irTrace = fmap (\uid' -> findWithDefault uid' uid' names) $ editMap $ irModuleTrace claferEnv' - return $ ClaferIGEnv claferEnv' igArgs constraints claferModel qNameMaps uidIClaferMap' sMap irTrace+ return $ ClaferIGEnv claferEnv' igArgs{bitwidth = bitwidth'} constraints claferModel modelFiles' (file claferArgs') qNameMaps uidIClaferMap' sMap irTrace dynamic+ (Set.map ("this/" ++) $ emptyAbstracts ir) names where- editMap :: (Map.Map Span [Ir]) -> (Map.Map Integer String) -- Map Line Number to Clafer Name+ editMap :: Map.Map Span [Ir] -> Map.Map Integer String -- Map Line Number to Clafer Name editMap =- fromList . removeConstraints . Data.List.foldr (\(num, ir) acc -> case (getIClafer ir) of+ fromList . removeConstraints . Data.List.foldr (\(num, ir) acc -> case getIClafer ir of Just (IClafer _ _ _ _ uid' _ _ _ _ _ _) -> (num, uid') : acc- _ -> acc) [] . tail . (Data.List.foldr (\((Span (Pos l1 _) (Pos l2 _)), irs) acc -> (zip [l1..l2] (replicate (fromIntegral $ l2 - l1 + 1) irs)) ++ acc) []) . toList+ _ -> acc) [] . (Data.List.foldr (\((Span (Pos l1 _) (Pos l2 _)), irs) acc -> (zip [l1..l2] (replicate (fromIntegral $ l2 - l1 + 1) irs)) ++ acc) []) . toList getIClafer :: [Ir] -> Maybe IClafer getIClafer [] = Nothing getIClafer ((IRClafer c):_) = Just c@@ -207,22 +261,42 @@ removeConstraints :: [(Integer, String)] -> [(Integer, String)] removeConstraints = map swap . reverse . toList . fromList . reverse . map swap - callClaferTranslator code =- mapLeft ClaferErrs $ runClafer claferArgs $ do+ callClaferTranslator claferArgs' code =+ mapLeft ClaferErrs $ runClafer claferArgs'{mode = [Alloy], keep_unused = True, no_stats = True} $ do addModuleFragment code parse iModule <- desugar Nothing compile iModule results <- generate- let (Just alloyResult) = Map.lookup Alloy results- return (claferEnv alloyResult, outputCode alloyResult, mappingToAlloy alloyResult, stringMap alloyResult)+ case Map.lookup Alloy results of+ Nothing ->+ throwErr (ClaferErr "No Alloy compilation result." :: ClaferSErr)+ -- e.g., a model with decimals, reals or doubles, which Alloy does not support+ (Just NoCompilerResult{reason = reason'}) ->+ throwErr (ClaferErr reason' :: ClaferSErr)+ -- a dynamic model compiles to a temporal Alloy model (tmp.als)+ (Just alloyResult) ->+ return (claferEnv alloyResult, outputCode alloyResult, mappingToAlloy alloyResult, stringMap alloyResult, extension alloyResult == "tmp.als") mapLeft f (Left l) = Left $ f l mapLeft _ (Right r) = Right r- claferArgs = defaultClaferArgs{mode = [Alloy], keep_unused = True, no_stats = True,flatten_inheritance = flatten_inheritance_comp igArgs, no_layout = no_layout_comp igArgs, check_duplicates = check_duplicates_comp igArgs, skip_resolver = skip_resolver_comp igArgs, scope_strategy = scope_strategy_comp igArgs}+ -- the options given to claferIG take precedence over the files' options+ claferArgs = defaultClaferArgs{file = claferFile', imports = imports_comp igArgs, import_root = import_root_comp igArgs, public_imports = public_imports_comp igArgs, import_base = import_base_comp igArgs, flatten_inheritance = flatten_inheritance_comp igArgs, no_layout = no_layout_comp igArgs, check_duplicates = check_duplicates_comp igArgs, skip_resolver = skip_resolver_comp igArgs, scope_strategy = scope_strategy_comp igArgs, trace_len = fromMaybe (trace_len defaultClaferArgs) (tl_comp igArgs)} claferFile' = claferModelFile igArgs- bitwidth' = bitwidth igArgs+ -- the bitwidth required to store the given integer+ requiredBitwidth :: Integer -> Integer+ requiredBitwidth n = ceiling $ logBase (2 :: Double) $ fromInteger $ 2 * n + 1 +-- | The errors as the compiler reports them, with the file and the position in it:+-- @Parse failed at a.cfr:3:5...@, @Compile error at a.cfr:3:5...@, or @Error...@, then the message.+inFiles :: [ModelFile] -> ClaferErrs -> ClaferErrs+inFiles files (ClaferErrs errs') = ClaferErrs $ map inFile errs'+ where+ inFile (ParseErr ErrPos{modelPos = Pos l c} msg') = ClaferErr $ "Parse failed at " ++ at l c ++ "...\n" ++ msg'+ inFile (SemanticErr ErrPos{modelPos = Pos l c} msg') = ClaferErr $ "Compile error at " ++ at l c ++ "...\n" ++ msg'+ inFile (ClaferErr msg') = ClaferErr $ "Error...\n" ++ msg'+ at l c = let (path, l') = modelPosition files l in path ++ ":" ++ show l' ++ ":" ++ show c + strictReadFile :: FilePath -> IO String strictReadFile filePath = do@@ -235,7 +309,11 @@ getAlloyModel :: MonadIO m => ClaferIGT m String getAlloyModel = ClaferIGT $ lift AlloyIG.getAlloyModel +-- | The folder of the temporary files of Alloy in this session, which alloyIG removes when it exits+getSessionTmpdir :: MonadIO m => ClaferIGT m FilePath+getSessionTmpdir = ClaferIGT $ lift AlloyIG.sessionTmpdir + solve :: MonadIO m => ClaferIGT m () solve = ClaferIGT $ lift AlloyIG.sendResolveCommand @@ -244,7 +322,7 @@ getClafers = do sigs <- ClaferIGT $ lift AlloyIG.getSigs- return $ map sigToClaferName sigs+ mapM claferNameOfSig sigs getGlobalScope :: MonadIO m => ClaferIGT m Integer@@ -253,8 +331,7 @@ getBitwidth :: MonadIO m => ClaferIGT m Integer getBitwidth = do- claferIGArgs' <- getClaferIGArgs- return $ bitwidth claferIGArgs'+ bitwidth <$> getClaferIGArgs setGlobalScope :: MonadIO m => Integer -> ClaferIGT m () setGlobalScope scope = ClaferIGT $ lift $ AlloyIG.sendSetGlobalScopeCommand scope@@ -282,36 +359,63 @@ setScope :: MonadIO m => Integer -> (String, Integer) -> ClaferIGT m (Either String ()) setScope value (sigName, _) = setAlloyScope value sigName +-- | Whether the clafer of the sig has no instances whatever its scope: an abstract clafer that no+-- concrete clafer inherits from. Its scope stays 0; Alloy would otherwise give it atoms of its own.+hasNoInstances :: Monad m => String -> ClaferIGT m Bool+hasNoInstances sigName = Set.member sigName <$> fetches emptySigs+ setAlloyScope :: MonadIO m => Integer -> String -> ClaferIGT m (Either String ()) setAlloyScope value sigName = do- subset <- ClaferIGT $ lift $ AlloyIG.sendSetScopeCommand sigName value- runExceptT $ maybe (return ()) throwError $ sigToClaferName <$> subset+ empty' <- hasNoInstances sigName+ subset <- ClaferIGT $ lift $ AlloyIG.sendSetScopeCommand sigName (if empty' then 0 else value)+ subsetName <- traverse claferNameOfSig subset+ runExceptT $ maybe (return ()) throwError subsetName +-- | The assertions of the model, with their names in the Alloy model+getAssertions :: MonadIO m => ClaferIGT m [(String, ConstraintInfo)]+getAssertions = do+ env <- getClaferEnv+ modelFiles' <- getModelFiles+ return $ parseAssertions modelFiles' $ fst3 $ fromJust $ cIr env +-- | The counterexample of an assertion within the scopes and the maximum trace length, if any,+-- which leaves the next solution of the model as it is+checkAssertion :: MonadIO m => String -> ClaferIGT m (Maybe (ClaferSolution, String))+checkAssertion assertion = do+ claferIGArgs' <- getClaferIGArgs+ uidIClaferMap' <- getUIDIClaferMap+ toUid <- getToUid+ dynamic <- isDynamicModel+ sMap <- getStrMap+ xmlSolution <- ClaferIGT $ lift $ AlloyIG.sendCheckCommand assertion+ return $ fmap (\xml -> (xmlToSolution toUid dynamic (useUids claferIGArgs') (addTypes claferIGArgs') uidIClaferMap' xml sMap, xml)) xmlSolution+ next :: MonadIO m => ClaferIGT m Instance next = do env <- getClaferEnv claferIGArgs' <- getClaferIGArgs uidIClaferMap' <- getUIDIClaferMap+ toUid <- getToUid let useUids' = useUids claferIGArgs' addTypes' = addTypes claferIGArgs' constraints' <- getConstraints+ dynamic <- isDynamicModel xmlSolution <- ClaferIGT $ lift AlloyIG.sendNextCommand sMap <- getStrMap case xmlSolution of- Just xml -> return $ Instance (xmlToModel useUids' addTypes' uidIClaferMap' xml sMap) xml+ Just xml -> return $ Instance (xmlToSolution toUid dynamic useUids' addTypes' uidIClaferMap' xml sMap) xml Nothing -> do ClaferIGT $ lift AlloyIG.sendSaveStateCommand -- Generating counterexample modifies the state. If we ever want to -- rerun the original model, we need to restore the state. AlloyIG.UnsatCore core <- ClaferIGT $ lift AlloyIG.sendUnsatCoreCommand- c <- counterexample env core useUids' addTypes' uidIClaferMap' constraints' sMap+ c <- counterexample (xmlToSolution toUid dynamic) env core useUids' addTypes' uidIClaferMap' constraints' sMap ClaferIGT $ lift AlloyIG.sendRestoreStateCommand return c where- counterexample env' originalCore useUids'' addTypes'' uidIClaferMap'' constraints' sMap = counterexample' env' originalCore [] useUids'' addTypes'' uidIClaferMap'' constraints' sMap+ counterexample toSolution env' originalCore useUids'' addTypes'' uidIClaferMap'' constraints' sMap = counterexample' env' originalCore [] useUids'' addTypes'' uidIClaferMap'' constraints' sMap where counterexample' env'' core removed useUids''' addTypes''' uidIClaferMap''' constraints'' sMap' = case msum $ findRemovable env'' core constraints'' of@@ -321,7 +425,7 @@ xmlSolution <- ClaferIGT $ lift AlloyIG.sendNextCommand case xmlSolution of Just xml -> return $- UnsatCore (catMaybes $ findRemovable env'' core constraints'') (Just $ Counterexample (reverse $ remove : removed) (xmlToModel useUids''' addTypes''' uidIClaferMap''' xml sMap') xml)+ UnsatCore (catMaybes $ findRemovable env'' core constraints'') (Just $ Counterexample (reverse $ remove : removed) (toSolution useUids''' addTypes''' uidIClaferMap''' xml sMap') xml) Nothing -> do AlloyIG.UnsatCore core' <- ClaferIGT $ lift AlloyIG.sendUnsatCoreCommand@@ -329,14 +433,50 @@ Nothing -> -- It is possible that none of the constraints are removable return NoInstance - xmlToModel :: Bool -> Bool -> UIDIClaferMap -> String -> (Map Int String) -> ClaferModel- xmlToModel useUids' addTypes' uidIClaferMap' xml sMap = (sugarClaferModel useUids' addTypes' uidIClaferMap' $ buildClaferModel $ parseSolution xml) sMap+-- | The instance of a static model, or the trace of a dynamic model, given the UIDs of the+-- clafers by their Alloy names (for --useuids)+xmlToSolution :: (String -> String) -> Bool -> Bool -> Bool -> UIDIClaferMap -> String -> Map Int String -> ClaferSolution+xmlToSolution toUid False useUids' addTypes' uidIClaferMap' xml sMap = ClaferInstance $ (sugarClaferModel toUid useUids' addTypes' uidIClaferMap' $ buildClaferModel $ parseSolution xml) sMap+xmlToSolution toUid True useUids' addTypes' uidIClaferMap' xml sMap = ClaferTrace (sugarClaferStates toUid useUids' addTypes' uidIClaferMap' (map buildStateModel states) sMap) loopState+ where+ (states, loopState) = parseTrace xml +-- | A trace with the same states as the trace given last before the given state, which differs+-- from the traces given so far, if any+fork :: MonadIO m => Integer -> ClaferIGT m Instance+fork state = otherTrace $ AlloyIG.sendForkCommand state++-- | A trace whose configuration, its clafers that do not change over time, differs from those of+-- the traces given so far, or an instance of a static model whose structure, its clafers without+-- the values of their references, differs from those of the instances given so far, if any+nextConfiguration :: MonadIO m => ClaferIGT m Instance+nextConfiguration = otherTrace AlloyIG.sendNextConfigurationCommand++otherTrace :: MonadIO m => AlloyIGT m (Maybe String) -> ClaferIGT m Instance+otherTrace command = do+ claferIGArgs' <- getClaferIGArgs+ uidIClaferMap' <- getUIDIClaferMap+ toUid <- getToUid+ sMap <- getStrMap+ dynamic <- isDynamicModel+ xmlSolution <- ClaferIGT $ lift command+ return $ case xmlSolution of+ Just xml -> Instance (xmlToSolution toUid dynamic (useUids claferIGArgs') (addTypes claferIGArgs') uidIClaferMap' xml sMap) xml+ Nothing -> NoInstance++-- | Whether the model is dynamic, with traces as its solutions+isDynamicModel :: Monad m => ClaferIGT m Bool+isDynamicModel = fetches dynamicModel++-- | Sets the maximum length of the traces of a dynamic model+setMaxTraceLength :: MonadIO m => Integer -> ClaferIGT m ()+setMaxTraceLength traceLength = ClaferIGT $ lift $ AlloyIG.sendSetMaxTraceLengthCommand traceLength+ reload :: MonadIO m => ClaferIGT m (Either ClaferErrs ()) reload = runExceptT $ do- globalScope <- lift $ getGlobalScope- claferIGArgs' <- lift $ getClaferIGArgs+ globalScope <- lift getGlobalScope+ claferIGArgs' <- lift getClaferIGArgs env <- ExceptT $ ClaferIGT $ lift $ load claferIGArgs' lift $ set env lift $ setGlobalScope globalScope@@ -358,22 +498,44 @@ quit = ClaferIGT $ lift AlloyIG.sendQuitCommand +-- | The clafer's name for an Alloy signature (this/name): its _ident, which its UID or Alloy+-- name need not contain, e.g., size for x__size, or a' for a_prime.+claferNameOfSig :: MonadIO m => String -> ClaferIGT m String+claferNameOfSig sig = do+ uidIClaferMap' <- getUIDIClaferMap+ let name = sigToClaferName sig+ return $ maybe name _ident $ findIClafer uidIClaferMap' name++-- | The Alloy name of a signature, without this/. sigToClaferName :: String -> String-sigToClaferName n =- case snd $ break ('_' ==) n of- [] -> n- x -> tail x+sigToClaferName sig = fromMaybe sig $ stripPrefix "this/" sig +-- | The UIDs of the clafers by their Alloy names.+getToUid :: Monad m => ClaferIGT m (String -> String)+getToUid = fromAlloyName <$> fetches alloyNameMap++-- | The signature of a clafer given its UID: this/ and its Alloy name.+sigOfUID :: Monad m => UID -> ClaferIGT m String+sigOfUID uid' = do+ names <- fetches alloyNameMap+ return $ "this/" ++ findWithDefault uid' uid' names++-- | The UID of a clafer given its signature.+uidOfSig :: Monad m => String -> ClaferIGT m UID+uidOfSig sig = do+ names <- fetches alloyNameMap+ return $ fromAlloyName names $ sigToClaferName sig+ findRemovable :: ClaferEnv -> [Span] -> [Constraint] -> [Maybe Constraint] findRemovable env core constraints' = let absIDs = foldMapIR getId $ getIMod $ fromJust $ cIr env in Data.List.filter (removeAbsZero absIDs ) $ map (\c -> find ((== c) . range) constraints') core where- removeAbsZero :: (Seq.Seq String) -> Maybe Constraint -> Bool+ removeAbsZero :: Seq.Seq String -> Maybe Constraint -> Bool removeAbsZero absIDs (Just (UpperCardinalityConstraint _ (ClaferInfo uID (Cardinality 0 (Just 0))))) = ((Seq.elemIndexL uID absIDs)==Nothing) removeAbsZero _ _ = True- getId :: Ir -> (Seq.Seq String)- getId (IRClafer (IClafer _ True _ uID _ _ _ _ _ _ _)) = Seq.singleton uID+ getId :: Ir -> Seq.Seq String+ getId (IRClafer (IClafer _ IClaferModifiers{_abstract=True} _ uID _ _ _ _ _ _ _)) = Seq.singleton uID getId _ = mempty getIMod :: (IModule, GEnv, Bool) -> IModule
src/Language/Clafer/IG/ClaferModel.hs view
@@ -20,7 +20,7 @@ SOFTWARE. -} -module Language.Clafer.IG.ClaferModel (ClaferModel(..), Clafer(..), Id(..), Value(..), c_name, buildClaferModel, traverseModel) where+module Language.Clafer.IG.ClaferModel (ClaferModel(..), Clafer(..), Id(..), Value(..), ClaferSolution(..), c_name, buildClaferModel, buildStateModel, solutionModels, traverseModel) where import Data.List import Data.Either@@ -31,7 +31,8 @@ -- | Clafer model instance data ClaferModel = ClaferModel {c_topLevel::[Clafer]}-data Clafer = Clafer {c_id::Id, c_value::Maybe Value, c_children::[Clafer]} deriving Eq+-- | An instance of a clafer: its name, the UID of its clafer, its value and its children+data Clafer = Clafer {c_id::Id, c_uid::String, c_value::Maybe Value, c_children::[Clafer]} deriving Eq data Value = AliasValue {c_alias::Id} | IntValue {v_value::Int} | StringValue {v_str ::String} deriving (Show, Eq) c_name :: Clafer -> String@@ -60,7 +61,7 @@ instance Show Clafer where show clafer = displayClafer "" clafer where- displayClafer indent (Clafer id value children) =+ displayClafer indent (Clafer id _ value children) = indent ++ i_name id ++ maybe "" displayValue value ++ "\n" ++ concatMap (displayClafer $ indent ++ " ") children displayValue (AliasValue alias) = " -> " ++ i_name alias@@ -169,26 +170,49 @@ buildClaferModel :: Solution -> ClaferModel-buildClaferModel solution =- ClaferModel $ removeDups [] $ lefts $ map buildClafer (getRoots ftree)+buildClaferModel solution = buildClafers solution ftree (getRoots ftree) where- sigMap = buildSigMap solution ftree = buildFamilyTree solution +-- | The instance in a state of a trace of a dynamic model. The sigs of a dynamic model are pools+-- of atoms, which exist in every state; the clafers that exist in the state are those reachable+-- from the root through their containment relations (r_c0_name). The parent relations+-- (p_c0_name) of the atoms are static, and do not belong to the tree.+buildStateModel :: Solution -> ClaferModel+buildStateModel solution = buildClafers solution ftree (getChildren (Id "root" 0) ftree)+ where+ ftree = buildFamilyTree solution{s_fields = filter isTreeField $ s_fields solution}+ isTreeField Field{f_label = label} = "r_" `isPrefixOf` label || "_ref" `isSuffixOf` label++-- | A solution of a model: an instance of a static model, or a trace of a dynamic model, whose+-- states are instances, and the state to which its last state loops back+data ClaferSolution = ClaferInstance ClaferModel | ClaferTrace [ClaferModel] Int++-- | The instances of a solution: the instance, or the states of the trace+solutionModels :: ClaferSolution -> [ClaferModel]+solutionModels (ClaferInstance model) = [model]+solutionModels (ClaferTrace states _) = states++buildClafers :: Solution -> FamilyTree -> [Node] -> ClaferModel+buildClafers solution ftree nodes =+ ClaferModel $ removeDups [] $ lefts $ map buildClafer nodes+ where+ sigMap = buildSigMap solution+ removeDups :: [Clafer] -> [Clafer] -> [Clafer] removeDups acc [] = acc- removeDups acc (m:ms) = if (m `elem` ms) then removeDups acc ms- else removeDups (m{c_children = (removeDups [] $ c_children m)} : acc) ms+ removeDups acc (m:ms) = if m `elem` ms then removeDups acc ms+ else removeDups (m{c_children = removeDups [] $ c_children m} : acc) ms intType = s_id $ findWithDefault (error "Missing Int sig") "Int" sigMap - singleton [] = Nothing- singleton [x] = Just x- singleton xs = error $ "Received more than one value " ++ show xs+ checkSingle [] = Nothing+ checkSingle [x] = Just x+ checkSingle xs = error $ "Received more than one value " ++ show xs buildClafer :: Node -> Either Clafer Value buildClafer (ClaferNode id _) =- Left $ Clafer id (singleton $ nub valueChildren) claferChildren+ Left $ Clafer id (i_name id) (checkSingle $ nub valueChildren) claferChildren where (claferChildren, valueChildren) = partitionEithers $ map buildClafer children children = getChildren id ftree
src/Language/Clafer/IG/CommandLine.hs view
@@ -1,4 +1,5 @@-{-# LANGUAGE NamedFieldPuns #-}+{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}+{-# HLINT ignore "Use camelCase" #-} {- Copyright (C) 2012-2017 Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>@@ -28,21 +29,24 @@ import Language.ClaferT import Language.Clafer.Intermediate.Intclafer import Language.Clafer.IG.ClaferIG+import Language.Clafer.Import (modelPosition) import Language.Clafer.IG.ClaferModel import Language.Clafer.IG.CommandLineParser import Language.Clafer.IG.Constraints-import Language.Clafer.IG.JSONGenerator+import Language.Clafer.IG.SolutionView import Language.Clafer.Comments import Language.Clafer.JSONMetaData import Language.Clafer.QNameUID import qualified Language.Clafer.IG.AlloyIGInterface as AlloyIG+import Control.Monad+import Control.Monad.Trans+import Control.Monad.IO.Class import Control.Monad.Except import Data.Char import Data.IORef import Data.List import Data.Monoid import Data.Foldable hiding (mapM_, maximum, find, elem, notElem, foldr, any, concat)-import qualified Data.StringMap as SMap import qualified Data.Map as Map import Data.Maybe import System.Console.Haskeline@@ -51,11 +55,20 @@ import qualified Text.Parsec.Error as E import Prelude -data AutoComplete = Auto_Command | Auto_Clafer | Auto_ClaferInstance | Auto_UnsatCoreMinimization | Auto_Space | Auto_Digit | No_Auto deriving Show+data AutoComplete+ = Auto_Command+ | Auto_Clafer+ | Auto_ClaferInstance+ | Auto_UnsatCoreMinimization+ | Auto_Space+ | Auto_Digit+ | No_Auto deriving Show data AutoCompleteContext = AutoCompleteContext {clafers::IORef [String], claferInstances::IORef [String]} -data Context = Context {currentAlloyInstance::Maybe String, saved::[ClaferModel], unsaved::[ClaferModel], autoCompleteContext::AutoCompleteContext}+-- | The solutions shown so far, the most recent first, and whether they are shown as the changes+-- from the previous snapshot+data Context = Context {currentAlloyInstance::Maybe String, saved::[ClaferSolution], unsaved::[ClaferSolution], autoCompleteContext::AutoCompleteContext, diffView::Bool} -- | Interactive session interface runCommandLine :: ClaferIGT IO ()@@ -68,11 +81,12 @@ claferInstancesRef <- liftIO $ newIORef [] let autoCompleteContext = AutoCompleteContext clafersRef claferInstancesRef+ diffView' <- diff <$> getClaferIGArgs runInputT Settings { complete = completeFunc autoCompleteContext, historyFile = Nothing, autoAddHistory = True- } $ loop Next (Context Nothing [] [] autoCompleteContext)+ } $ loop Next (Context Nothing [] [] autoCompleteContext diffView') where @@ -83,21 +97,8 @@ loop Next context = do solution <- lift next- claferIGArgs' <- lift getClaferIGArgs- uidIClaferMap' <- lift $ getUIDIClaferMap case solution of- Instance claferModel xml -> do- liftIO $ writeIORef (claferInstances $ autoCompleteContext context) $ map c_name (traverseModel claferModel)-- outputStrLn $ if json claferIGArgs'- then generateJSON uidIClaferMap' claferModel- else let- iNumber = show $ 1 + (length $ unsaved context)- in- "=== Instance " ++ iNumber ++ " Begin ===\n\n" ++- (show claferModel) ++- "\n--- Instance " ++ iNumber ++ " End ---\n\n"- nextLoop context{unsaved=claferModel:(unsaved context), currentAlloyInstance=Just xml}+ Instance claferSolution xml -> showNew claferSolution xml context UnsatCore core counterexample -> do liftIO $ hPutStrLn stderr "No instances found." liftIO $ hPutStrLn stderr "The following set of constraints cannot be satisfied in the current scope."@@ -107,14 +108,17 @@ printConstraints core case counterexample of- Just (Counterexample removed claferModel _) -> do+ Just (Counterexample removed claferSolution _) -> do liftIO $ hPutStrLn stderr "Altering the following constraints produced the following near-miss example:" printTransformations removed- outputStrLn $ show claferModel+ outputStrLn $ solutionText claferSolution Nothing -> return () nextLoop context NoInstance -> do- liftIO $ hPutStrLn stderr "No more instances found. Try increasing the scopes to get more instances (type 'h' for help)."+ dynamic <- lift isDynamicModel+ liftIO $ hPutStrLn stderr $ if dynamic+ then "No more traces found. Try increasing the scopes or the maximum trace length ('tl') to get more traces (type 'h' for help)."+ else "No more instances found. Try increasing the scopes to get more instances (type 'h' for help)." nextLoop context where printTransformation :: Constraint -> [Constraint] -> (String, [Constraint])@@ -180,13 +184,25 @@ "You can invoke the following commands as indicated by single quotes:\n" ++ "[tab] - print the available commands\n" ++ " - auto-complete command name, a clafer name, or clafer instance name in a given context\n" ++- "'n'ext, [enter] - to produce the next instance if available or to output a message that no more \n" ++- " instances exist within the given scope\n" +++ "'n'ext, [enter] - to produce the next solution if available, an instance of a static model or a trace\n" +++ " of a dynamic model, or to output a message that no more solutions exist within\n" +++ " the given scope\n" ++ "'i'ncrease - to increase the maximum number of instances of a given clafer or all clafers (scope)\n" ++ "'s'et - to set the maximum number of instances of a given clafer or all clafers (scope)\n" ++ "'m'axint, 'maxint' - to set the bitwidth by providing the largest integer\n" +++ "'tl' - to set the maximum length of the traces of a dynamic model\n" +++ "'d'iff - to show each next instance or state as its changes from the previous one, or in full\n" +++ " (+ appears, - disappears, ~ changes its value)\n" +++ "'fork' - to produce another trace with the same first states as the last trace\n" +++ "'config' - to produce a trace of a dynamic model whose clafers that do not change over time\n" +++ " differ from those of the traces so far, or an instance of a static model whose\n" +++ " clafers, without the values of their references, differ from those so far\n" +++ "'check' - to check the assertions of the model within the scopes and the maximum trace\n" +++ " length, and to give a counterexample of each one that fails\n" ++ "sa'v'e - to save all instances displayed so far or a counterexample to files named \n" ++ " <model file name>.cfr.<instance number>.data, one instance per file\n" +++ "'dot' - to save the most recent solution as a Graphviz graph, for a trace its states\n" +++ " and transitions, to <model file name>.cfr.<solution number>.dot\n" ++ "'q'uit - to quit the interactive session\n" ++ "'r'eload - to reload your clafer model\n" ++ "'h'elp - to display this menu options summary\n" ++@@ -205,6 +221,9 @@ "'s <number> [enter]'- to set for the clafers to <number>\n" ++ "'s <name> <number>' - to set for the clafer <name> to <number>\n" ++ "'f <name>' - to display a clafer <name>\n" +++ "'tl <number>' - to set the maximum trace length to <number>\n" +++ "'fork <number>' - to produce another trace with the states of the last trace before state <number>\n" +++ "'check <number>' - to check only the assertions on line <number>, or all of them if it is not positive\n" ++ "'setUnsatCoreMinimization fastest' - fastest but the worst\n" ++ "'setUnsatCoreMinimization medium'\n" ++ "'setUnsatCoreMinimization best' - best but slowest even for modest size cores"@@ -217,6 +236,43 @@ save unsaved (toInteger $ length saved) nextLoop context{saved=unsaved ++ saved, unsaved=[]} + loop SaveGraph context =+ do+ let solutions = unsaved context ++ saved context+ case solutions of+ [] -> outputStrLn "No solution yet: type 'n' for the first one."+ solution : _ -> do+ claferModelFile' <- lift getModelFileName+ let saveName = claferModelFile' ++ "." ++ show (length solutions) ++ ".dot"+ qNameMaps' <- lift getQNameMaps+ liftIO $ writeFile saveName $ if diffView context+ then solutionDiffDot (lpqName qNameMaps') solution+ else solutionDot solution+ outputStrLn $ "Saved to " ++ saveName+ nextLoop context++ loop (Check line) context =+ do+ allAssertions <- lift getAssertions+ let assertions = maybe allAssertions (\n -> filter (isOnLine n . snd) allAssertions) line+ dynamic <- lift isDynamicModel+ when (null assertions) $ outputStrLn $ maybe "The model has no assertions." (\n -> "The model has no assertion on line " ++ show n ++ ".") line+ (context', failed) <- foldM checkAssertion' (context, 0 :: Int) assertions+ let bounds = if dynamic then "the scopes and the maximum trace length" else "the scopes"+ unless (null assertions) $ outputStrLn $+ show (length assertions) ++ " assertion(s) checked within " ++ bounds ++ ": " ++ show failed ++ " with a counterexample."+ nextLoop context'+ where+ checkAssertion' (context', failed) (name, info) =+ do+ counterexample <- lift $ checkAssertion name+ case counterexample of+ Nothing -> outputStrLn ("No counterexample: " ++ show info) >> return (context', failed)+ Just (claferSolution, xml) -> do+ outputStrLn $ "Counterexample of: " ++ show info+ context'' <- display claferSolution xml context'+ return (context'', failed + 1)+ loop Reload context = do oldScopes <- lift getScopes@@ -248,8 +304,11 @@ newBw <- lift getBitwidth printBitwidthWarning newBw - oldScopes <- lift getScopes- mapM_ ( \(sigName', val') -> setAlloyScopeAndBitwidth bitwidth' (max 1 $ val'+inc') (sigToClaferName sigName') sigName') oldScopes+ -- the clafers without instances keep their scopes, 0+ oldScopes <- lift $ filterM (fmap not . hasNoInstances . fst) =<< getScopes+ mapM_ ( \(sigName', val') -> do+ claferName' <- lift $ claferNameOfSig sigName'+ setAlloyScopeAndBitwidth bitwidth' (max 1 $ val'+inc') claferName' sigName') oldScopes lift solve outputStrLn ("Global scope changed to " ++ show newGlobalScope) nextLoop context@@ -272,7 +331,7 @@ try $ do qNameMaps' <- lift $ lift $ getQNameMaps let uids = getUIDs qNameMaps' fqName- let sigs = map ("this/" ++) uids+ sigs <- lift $ lift $ mapM sigOfUID uids bitwidth' <- lift $ lift getBitwidth lift $ mapM_ (incAlloyScopeAndBitwidth bitwidth' inc' fqName) sigs@@ -285,7 +344,7 @@ try $ do qNameMaps' <- lift $ lift $ getQNameMaps let uids = getUIDs qNameMaps' qName- let sigs = map ((++) "this/") uids+ sigs <- lift $ lift $ mapM sigOfUID uids bitwidth' <- lift $ lift getBitwidth lift $ mapM_ (setAlloyScopeAndBitwidth bitwidth' val' qName) sigs@@ -302,6 +361,35 @@ printBitwidthIntRange newBitwidth nextLoop context + loop (SetMaxTraceLength traceLength) context =+ do+ dynamic <- lift isDynamicModel+ if not dynamic+ then outputStrLn "The model is static: its instances are not traces."+ else if traceLength < 1+ then outputStrLn "The trace length must be at least 1."+ else do+ lift $ setMaxTraceLength traceLength+ lift solve+ outputStrLn $ "The maximum trace length is " ++ show traceLength ++ "."+ nextLoop context++ loop (Fork state) context =+ do+ dynamic <- lift isDynamicModel+ if not dynamic+ then outputStrLn "The model is static: its instances are not traces." >> nextLoop context+ else otherSolution (fork state) ("No other trace has the states of the last trace before state " ++ show state ++ ".") context++ loop NextConfiguration context = otherSolution nextConfiguration "No solution has another configuration." context++ loop ToggleDiff context =+ do+ outputStrLn $ if diffView context+ then "The instances and states are shown in full."+ else "Each next instance or state is shown as its changes from the previous one."+ nextLoop context{diffView = not $ diffView context}+ loop (SetMaxInt newMaxInt) context = do when (newMaxInt >= 7) $ do@@ -317,33 +405,34 @@ globalScope <- lift getGlobalScope outputStrLn $ "Global scope = " ++ show globalScope originalScopes <- lift getScopes- -- remove the "this/" prefix- mapM_ printScope originalScopes+ -- by UID+ mapM_ (\(sigName, value) -> lift (uidOfSig sigName) >>= \uid' -> printScope (uid', value)) originalScopes nextLoop context where- printScope (sigName, value) =- outputStrLn $ " " ++ (drop 5 sigName) ++ " scope = " ++ show value+ printScope (uid', value) =+ outputStrLn $ " " ++ uid' ++ " scope = " ++ show value loop SaveScopes context = do globalScope <- lift getGlobalScope originalScopes <- lift getScopes- claferIGArgs' <- lift getClaferIGArgs+ modelFileName <- lift getModelFileName qNameMaps' <- lift getQNameMaps+ -- by UID+ sigUids <- lift $ mapM (uidOfSig . fst) originalScopes let globalScopeTuple = ("", globalScope)- -- remove the "this/" prefix- uidScopes = globalScopeTuple : (map (\(sigName, value) -> (drop 5 sigName, value)) originalScopes)- liftIO $ writeCfrScopeFile uidScopes qNameMaps' $ claferModelFile claferIGArgs'+ uidScopes = globalScopeTuple : zip sigUids (map snd originalScopes)+ liftIO $ writeCfrScopeFile uidScopes qNameMaps' modelFileName outputStrLn "Scopes saved to the `.cfr-scope` file." nextLoop context loop LoadScopes context = do- claferIGArgs' <- lift getClaferIGArgs+ modelFileName <- lift getModelFileName qNameMaps' <- lift getQNameMaps- maybeUidScopes <- liftIO $ readCfrScopeFile qNameMaps' $ claferModelFile claferIGArgs'+ maybeUidScopes <- liftIO $ readCfrScopeFile qNameMaps' modelFileName case maybeUidScopes of Nothing -> do outputStrLn "The `.cfr-scope` file does not exist. Use the command `saveScopes` to create one."@@ -353,18 +442,19 @@ (globalScopes, normalScopes) = partition (\(uid', _) -> null uid') uidScopes -- from the globalScopes, take the maximum globalScopeVals = map snd globalScopes- globalScope = maximum globalScopeVals- -- add the "this/" prefix- normalScopesAlloy = map (\(uid', scope) -> ("this/"++uid', scope)) normalScopes- lift $ setGlobalScope globalScope+ -- the sigs of the clafers+ normalSigs <- lift $ mapM (sigOfUID . fst) normalScopes+ let normalScopesAlloy = zip normalSigs (map snd normalScopes)+ -- a file may list only some clafers, without the global scope; then it stays+ unless (null globalScopeVals) $ lift $ setGlobalScope $ maximum globalScopeVals lift $ mapM_ (\(uid', val) -> setAlloyScope val uid') normalScopesAlloy outputStrLn "Scopes loaded from the `.cfr-scope` file." loop ShowScopes context loop (Find name) context = do case (unsaved context ++ saved context) of- model:_ ->- case find ((name ==) . c_name) $ traverseModel model of+ solution:_ ->+ case find ((name ==) . c_name) $ concatMap traverseModel $ solutionModels solution of Just clafer' -> outputStrLn $ show clafer' Nothing -> outputStrLn $ "\"" ++ name ++ "\" not found in the model." [] -> outputStrLn $ "No instance"@@ -389,30 +479,35 @@ let unSATs = map getConstraintInfo $ catMaybes $ findRemovable env core constraints' claferModel <- lift getClaferModel+ modelFiles' <- lift getModelFiles let commentLines = getCommentLines claferModel lineNumMap <- lift getlineNumMap - outputStrLn $ editModel claferModel commentLines unSATs lineNumMap scopesMap+ outputStrLn $ editModel claferModel commentLines unSATs lineNumMap scopesMap modelFiles' nextLoop context where- editModel :: String -> [Integer] -> [String] -> (Map.Map Integer String) -> (Map.Map String Integer) -> String- editModel model cLines unSATs lineNumMap scopesMap' =+ -- the lines of the model: each file under its name, with the numbers of its lines+ editModel model cLines unSATs lineNumMap scopesMap' modelFiles' = let claferLines = lines $ removeCommentsAndUnify model maxLineLength = maximum $ map length claferLines- in unlines $ editLines cLines unSATs (numberOfDigits $ length claferLines) maxLineLength scopesMap' lineNumMap (zip [1..] claferLines)+ shown = [ (modelPosition modelFiles' num, num, l) | (num, l) <- zip [1..] claferLines, not (num `elem` cLines && isEmptyLine l) ]+ header ((path, _), _, _) previous+ | fmap (\((p, _), _, _) -> p) previous == Just path = []+ | otherwise = ["--- " ++ path]+ in unlines $ concat $ zipWith (\line' previous -> header line' previous ++ [editLine unSATs (numberOfDigits $ length claferLines) maxLineLength scopesMap' lineNumMap line']) shown (Nothing : map Just shown) - editLines :: [Integer] -> [String] -> Int -> Int -> (Map.Map String Integer) -> (Map.Map Integer String) -> [(Integer, String)] -> [String]- editLines _ _ _ _ _ _ [] = []- editLines cLines unSATs m1 m2 scopesMap' lineNumMap ((num, l):rest) =- if (num `elem` cLines && isEmptyLine l)- then editLines cLines unSATs m1 m2 scopesMap' lineNumMap rest- else (show num ++ "." ++ (replicate (1 + m1 - (numberOfDigits $ fromIntegral num)) ' ') ++ (if (isUnSAT unSATs l num) then "> " else "| ") ++ l ++ (replicate (3 + m2 - (length l)) ' ') ++ (if (isUnSAT unSATs l num) then "<UnSAT " else "| ") ++ (addScopeVal scopesMap' (Map.lookup num lineNumMap)))- : editLines cLines unSATs m1 m2 scopesMap' lineNumMap rest+ editLine :: [(Maybe Integer, String)] -> Int -> Int -> (Map.Map String Integer) -> (Map.Map Integer String) -> ((FilePath, Integer), Integer, String) -> String+ editLine unSATs m1 m2 scopesMap' lineNumMap ((_, fileNum), num, l) =+ show fileNum ++ "." ++ (replicate (1 + m1 - (numberOfDigits $ fromIntegral fileNum)) ' ') ++ (if (isUnSAT unSATs l num) then "> " else "| ") ++ l ++ (replicate (3 + m2 - (length l)) ' ') ++ (if (isUnSAT unSATs l num) then "<UnSAT " else "| ") ++ (addScopeVal scopesMap' (Map.lookup num lineNumMap)) - isUnSAT :: [String] -> String -> Integer -> Bool- isUnSAT us l ln = getAny $ foldMap (\u -> Any (((safehead $ words u) == (safehead $ words l) && (safehead $ reverse $ words u) == (safehead $ reverse $ words l)) || (u `isInfixOf` l) || ("column" `isInfixOf` u && "line" `isInfixOf` u && (init $ head $ tail $ tail $ reverse $ words u) == show ln))) us+ -- a constraint with a position is on the line where it starts; a cardinality+ -- is on the line with the clafer's name and cardinality+ isUnSAT :: [(Maybe Integer, String)] -> String -> Integer -> Bool+ isUnSAT us l ln = getAny $ foldMap (\u -> Any $ case u of+ (Just line', _) -> line' == ln+ (Nothing, u') -> ((safehead $ words u') == (safehead $ words l) && (safehead $ reverse $ words u') == (safehead $ reverse $ words l)) || (u' `isInfixOf` l)) us safehead [] = [] safehead x = head x @@ -423,9 +518,9 @@ getCommentLines :: String -> [Integer] getCommentLines = foldr (\((Span (Pos l1 _) (Pos l2 _)), _) acc -> [l1..l2] ++ acc) [] . getComments - getConstraintInfo :: Constraint -> String- getConstraintInfo (UserConstraint _ info) = show info- getConstraintInfo x = show $ claferInfo x+ getConstraintInfo :: Constraint -> (Maybe Integer, String)+ getConstraintInfo (UserConstraint _ info@(ConstraintInfo _ (Span (Pos l _) _) _ _ _)) = (Just l, show info)+ getConstraintInfo x = (Nothing, show $ claferInfo x) loop ShowAlloyModel context = do@@ -467,6 +562,40 @@ nextLoop context + -- shows a new solution, the next one+ showNew claferSolution xml context = display claferSolution xml context >>= nextLoop++ -- shows a solution, which becomes the most recent one+ display claferSolution xml context =+ do+ claferIGArgs' <- lift getClaferIGArgs+ uidIClaferMap' <- lift getUIDIClaferMap+ qNameMaps' <- lift getQNameMaps+ liftIO $ writeIORef (claferInstances $ autoCompleteContext context) $ nub $ map c_name $ concatMap traverseModel $ solutionModels claferSolution++ let+ iNumber = 1 + length (unsaved context)+ previous = listToMaybe (unsaved context ++ saved context)+ outputStrLn $ if json claferIGArgs'+ then solutionJSON uidIClaferMap' claferSolution+ else if dot claferIGArgs'+ then (if diffView context then solutionDiffDot (lpqName qNameMaps') claferSolution else solutionDot claferSolution)+ else if diffView context+ then showSolutionDiff (lpqName qNameMaps') iNumber previous claferSolution+ else showSolution iNumber claferSolution+ return context{unsaved=claferSolution:(unsaved context), currentAlloyInstance=Just xml}++ -- shows a solution other than the next one: a fork, or another configuration+ otherSolution command none context =+ do+ if null (unsaved context ++ saved context)+ then outputStrLn "No solution yet: type 'n' for the first one." >> nextLoop context+ else do+ solution <- lift command+ case solution of+ Instance claferSolution xml -> showNew claferSolution xml context+ _ -> outputStrLn none >> nextLoop context+ nextLoop context = do minput <- getInputLine "claferIG> "@@ -477,14 +606,13 @@ Left msg -> outputStrLn (show msg) >> nextLoop context Right command -> loop command context - save :: MonadIO m => [ClaferModel] -> Integer -> InputT (ClaferIGT m) ()+ save :: MonadIO m => [ClaferSolution] -> Integer -> InputT (ClaferIGT m) () save [] _ = return () save (c:cs) counter = do- claferIGArgs' <- lift $ getClaferIGArgs+ claferModelFile' <- lift getModelFileName let- claferModelFile' = claferModelFile claferIGArgs' saveName = claferModelFile' ++ "." ++ (show counter) ++ ".data"- liftIO $ writeFile saveName (show c)+ liftIO $ writeFile saveName (solutionText c) outputStrLn $ "Saved to " ++ saveName save cs (counter + 1) @@ -498,6 +626,10 @@ setAlloyScopeAndBitwidth :: MonadIO m => Integer -> Integer -> String -> UID -> InputT (ClaferIGT m) () setAlloyScopeAndBitwidth bitwidth' newValue' fqName' sigName' = do+ empty' <- lift $ hasNoInstances sigName'+ if empty'+ then outputStrLn $ "Scope of " ++ fqName' ++ " (" ++ (drop 5 sigName') ++ ") stays 0: it has no instances, since no concrete clafer inherits from it or from the abstract clafer it is in"+ else do when (newValue' > allowedMaxInt bitwidth') $ do lift $ setBitwidth $ requiredBitwidth $ newValue' newBw <- lift $ getBitwidth@@ -507,7 +639,7 @@ outputStrLn $ "Scope of " ++ fqName' ++ " (" ++ (drop 5 sigName') ++ ") changed to " ++ show newValue' mergeScopes :: MonadIO m => [(UID, Integer)] -> [(UID, Integer)] -> ClaferIGT m ()-mergeScopes _ [] = return()+mergeScopes _ [] = return () mergeScopes oldScopes newScopes = do let mergedScopes = map (pickLargerScope oldScopes) newScopes mapM_ (\(uid', val) -> setAlloyScope val uid') mergedScopes@@ -515,8 +647,8 @@ pickLargerScope :: [(String, Integer)] -> (String, Integer) -> (String, Integer) pickLargerScope oldScopes (uid', val) = let- oldScopesMap = SMap.fromList oldScopes- oldVal = SMap.findWithDefault val uid' oldScopesMap+ oldScopesMap = Map.fromList oldScopes+ oldVal = Map.findWithDefault val uid' oldScopesMap in (uid', max val oldVal) -- | bitwidth required to store the given integer@@ -610,16 +742,16 @@ expectedMessages = mapMaybe expectedMessage messages +-- | The errors of loading a model, which give the file and the position in it. printError :: ClaferErrs -> [String] printError (ClaferErrs errs) = map printErr errs where printErr (ParseErr (ErrPos _ _ (Pos l c)) msg) =- "Parse error at line " ++ show l ++ ", column " ++ show c ++ ":\n " ++ msg+ "Parse failed at line " ++ show l ++ " column " ++ show c ++ "...\n" ++ msg printErr (SemanticErr (ErrPos _ _ (Pos l c)) msg) =- "Error at line " ++ show l ++ ", column " ++ show c ++ ":\n " ++ msg- printErr (ClaferErr msg) =- "Error:\n " ++ msg+ "Compile error at line " ++ show l ++ " column " ++ show c ++ "...\n" ++ msg+ printErr (ClaferErr msg) = msg -- only remove the contents while preserving the empty lines removeCommentsAndUnify :: String -> String@@ -660,6 +792,6 @@ intToFloat :: Integer -> Float intToFloat = fromInteger . toInteger -fromJustShow :: (Maybe Integer) -> String+fromJustShow :: Maybe Integer -> String fromJustShow (Just x) = show x fromJustShow Nothing = "Nothing"
src/Language/Clafer/IG/CommandLineParser.hs view
@@ -38,7 +38,13 @@ SetScope String Integer | SetBitwidth Integer | SetMaxInt Integer |+ SetMaxTraceLength Integer |+ ToggleDiff |+ Fork Integer |+ NextConfiguration |+ Check (Maybe Integer) | Save |+ SaveGraph | Quit | Reload | Help |@@ -127,10 +133,16 @@ ("b", setBitwidthCommand): ("m", setMaxIntCommand): ("maxint", setMaxIntCommand):+ ("tl", setMaxTraceLengthCommand):+ ("d", toggleDiffCommand):+ ("fork", forkCommand):+ ("config", nextConfigurationCommand):+ ("check", checkCommand): ("n", nextCommand): ("f", findCommand): ("q", quitCommand): ("v", saveCommand):+ ("dot", saveGraphCommand): ("r", reloadCommand): ("scope", showScopesCommand): ("saveScopes", saveScopesCommand):@@ -154,12 +166,24 @@ setBitwidthCommand = setBitwidth setMaxIntCommand :: Parser Command setMaxIntCommand = setMaxInt+setMaxTraceLengthCommand :: Parser Command+setMaxTraceLengthCommand = SetMaxTraceLength `liftM` (gap >> number)+forkCommand :: Parser Command+forkCommand = Fork `liftM` (gap >> number)+nextConfigurationCommand :: ParsecT String () Identity Command+nextConfigurationCommand = return NextConfiguration+checkCommand :: Parser Command+checkCommand = (Check . mfilter (> 0)) `liftM` optionMaybe (try (gap >> signedNumber))+toggleDiffCommand :: ParsecT String () Identity Command+toggleDiffCommand = return ToggleDiff nextCommand :: ParsecT String () Identity Command nextCommand = return Next quitCommand :: ParsecT String () Identity Command quitCommand = return Quit saveCommand :: ParsecT String () Identity Command saveCommand = return Save+saveGraphCommand :: ParsecT String () Identity Command+saveGraphCommand = return SaveGraph reloadCommand :: ParsecT String () Identity Command reloadCommand = return Reload findCommand :: ParsecT String () Identity Command
src/Language/Clafer/IG/Constraints.hs view
@@ -22,13 +22,14 @@ SOFTWARE. -} -module Language.Clafer.IG.Constraints (Constraint(..), Cardinality(..), ClaferInfo(..), ConstraintInfo(..), isLowerCardinalityConstraint, isUpperCardinalityConstraint, lookupConstraint, parseConstraints) where+module Language.Clafer.IG.Constraints (Constraint(..), Cardinality(..), ClaferInfo(..), ConstraintInfo(..), isLowerCardinalityConstraint, isUpperCardinalityConstraint, lookupConstraint, parseConstraints, parseAssertions, isOnLine) where import Data.List import Data.Maybe import Data.Ord import Language.Clafer import Language.Clafer.Front.AbsClafer (Span(..))+import Language.Clafer.Import (ModelFile, modelText, modelPosition) import Language.Clafer.Intermediate.Intclafer import qualified Language.Clafer.Intermediate.Intclafer as I @@ -60,11 +61,17 @@ show (ClaferInfo uniqueId cardinality) = uniqueId ++ " " ++ show cardinality -data ConstraintInfo = ConstraintInfo {pId::String, pos::Span, syntax::String} deriving Eq+-- | A constraint of the model: its position in the complete model, its text, and its position+-- as shown, the file and the position in it (@file.cfr:3:5@).+data ConstraintInfo = ConstraintInfo {pId::String, pos::Span, syntax::String, position::String, fileLine::Integer} deriving Eq instance Show ConstraintInfo where- show ConstraintInfo{pos = Span (Pos l c) _, syntax} = syntax ++ " (line " ++ show l ++ ", column " ++ show c ++ ")"+ show ConstraintInfo{syntax, position} = syntax ++ " (" ++ position ++ ")" +-- | Whether a constraint spans the given line of its file.+isOnLine :: Integer -> ConstraintInfo -> Bool+isOnLine n ConstraintInfo{pos = Span (Pos l1 _) (Pos l2 _), fileLine} = fileLine <= n && n <= fileLine + l2 - l1+ isLowerCardinalityConstraint :: Constraint -> Bool isLowerCardinalityConstraint LowerCardinalityConstraint{} = True isLowerCardinalityConstraint _ = False@@ -88,14 +95,14 @@ cs -> minimumBy (comparing $ to . range) cs -parseConstraints :: String -> IModule -> [(Span, IrTrace)] -> [Constraint]-parseConstraints claferModel imodule mapping =+parseConstraints :: [ModelFile] -> IModule -> [(Span, IrTrace)] -> [Constraint]+parseConstraints modelFiles imodule mapping = mapMaybe (uncurry convert) mapping where clafers = _mDecls imodule >>= subclafers pexps = (mapMaybe constraint $ _mDecls imodule ++ concatMap _elements clafers) >>= subexpressions convert s IrPExp{pUid} =- Just $ UserConstraint s $ ConstraintInfo pUid (_inPos $ findPExp pUid) $ extract $ _inPos $ findPExp pUid+ Just $ UserConstraint s $ constraintInfoOf modelFiles $ findPExp pUid convert s LowerCard{pUid, isGroup = False} = Just $ LowerCardinalityConstraint s $ claferInfo pUid convert s UpperCard{pUid, isGroup = False} =@@ -106,21 +113,56 @@ findPExp pUid = fromMaybe (error $ "Unknown constraint " ++ pUid) $ find ((== pUid) . _pid) pexps findClafer pUid = fromMaybe (error $ "Unknown clafer " ++ pUid) $ find ((== pUid) . _uid) clafers- text = lines claferModel- extract (Span (Pos l1 c1) (Pos l2 c2))+ convertCard (l, -1) = Cardinality l Nothing+ convertCard (l, h) = Cardinality l $ Just h+ claferInfo pUid =+ ClaferInfo (_ident claf) $ convertCard $ fromJust $ _card claf+ where+ claf = findClafer pUid+++-- | The assertions of the model, in the order of the model, with their names in the Alloy output.+parseAssertions :: [ModelFile] -> IModule -> [(String, ConstraintInfo)]+parseAssertions modelFiles imodule =+ [ (assertionName pexp, constraintInfoOf modelFiles pexp) | pexp <- sortOn _inPos $ mapMaybe assertion elements ]+ where+ elements = _mDecls imodule ++ concatMap _elements (_mDecls imodule >>= subclafers)+ assertion (IEConstraint False pexp) = Just pexp+ assertion _ = Nothing+++-- | The information of a constraint: its text and position in the files of the model.+constraintInfoOf :: [ModelFile] -> PExp -> ConstraintInfo+constraintInfoOf modelFiles pexp = ConstraintInfo (_pid pexp) (_inPos pexp) (extract $ _inPos pexp) (showPosition $ _inPos pexp) (positionLine $ _inPos pexp)+ where+ -- the columns count a tab up to the next multiple of 8, as the compiler does+ text = map expandTabs $ lines $ modelText modelFiles+ showPosition (Span (Pos l c) _) = let (path, l') = modelPosition modelFiles l in path ++ ":" ++ show l' ++ ":" ++ show c+ positionLine (Span (Pos l _) _) = snd $ modelPosition modelFiles l+ -- an expression's span ends before the parentheses that close its last operand, e.g.,+ -- `initially (a --> b` of `initially (a --> b)`, which are added+ extract (Span (Pos l1 c1) (Pos l2 c2)) = closeParentheses (extract' l1 c1 l2 c2) (drop (fromInteger $ c2 - 1) $ text !! (fromInteger $ l2 - 1))+ extract' l1 c1 l2 c2 | l1 == l2 = drop (fromInteger $ c1 - 1) $ take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l1 - 1) | otherwise = unlines $ f1 : fs ++ [fn] where f1 = drop (fromInteger $ c1 - 1) $ text !! (fromInteger $ l1 - 1) fs = map (text !!) [(fromInteger $ l1) .. (fromInteger $ l2 - 2)] fn = take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l2 - 1)- convertCard (l, -1) = Cardinality l Nothing- convertCard (l, h) = Cardinality l $ Just h- claferInfo pUid =- ClaferInfo (_ident claf) $ convertCard $ fromJust $ _card claf+ closeParentheses extracted rest+ | open > 0, ')' : rest' <- dropWhile (== ' ') rest = closeParentheses (extracted ++ takeWhile (== ' ') rest ++ ")") rest'+ | otherwise = extracted where- claf = findClafer pUid+ open = length (filter (== '(') extracted) - length (filter (== ')') extracted) ++-- | The line with its tabs as spaces, up to the next multiple of 8+expandTabs :: String -> String+expandTabs = expand 0+ where+ expand column ('\t' : rest) = let n = 8 - column `mod` 8 in replicate n ' ' ++ expand (column + n) rest+ expand column (x : rest) = x : expand (column + 1) rest+ expand _ [] = [] subclafers :: IElement -> [IClafer] subclafers (IEClafer claf) = claf : (_elements claf >>= subclafers)
src/Language/Clafer/IG/JSONGenerator.hs view
@@ -19,6 +19,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -}+{-# LANGUAGE OverloadedStrings #-} module Language.Clafer.IG.JSONGenerator (generateJSON) where @@ -26,17 +27,21 @@ import Language.Clafer.Intermediate.Intclafer import qualified Language.Clafer.IG.ClaferModel as M import Data.Maybe (fromJust)-import Data.Json.Builder+import Data.Aeson ((.=))+import Data.Aeson.Encoding (Series, encodingToLazyByteString, list, pair, pairs) import Data.String.Conversions import Prelude hiding (id) +-- | A JSON object, whose fields keep their order+type Object = Series+ -- | Generate a representation of the instance in JSON format generateJSON :: UIDIClaferMap -> M.ClaferModel -> String generateJSON uidIClaferMap' (M.ClaferModel topLevelClafers) =- convertString $ toJsonBS $ constructElements $ map (printClafer uidIClaferMap') topLevelClafers+ convertString $ encodingToLazyByteString $ pairs $ constructElements $ map (printClafer uidIClaferMap') topLevelClafers printClafer :: UIDIClaferMap -> M.Clafer -> Object-printClafer uidIClaferMap' (M.Clafer id value children) =+printClafer uidIClaferMap' (M.Clafer id _ value children) = map (printClafer uidIClaferMap') children `addElements` completeClaferObject where uid' = M.i_name id@@ -45,8 +50,9 @@ super' = getSuper iclafer reference' = getReference iclafer- (Just (cardMin, _)) = _card iclafer- (Just (_, cardMax)) = _card iclafer+ (cardMin, cardMax) = case _card iclafer of+ Just card' -> card'+ Nothing -> error $ "Function printClafer from JSONGenerator expects the cardinality of " ++ uid' -- Should never happen, the compiler sets every cardinality basicClaferObject = makeBasicClaferObject ident' uid' super' reference' cardMin cardMax addValue :: Maybe M.Value -> Object -> Object@@ -62,27 +68,27 @@ makeBasicClaferObject :: String -> String -> [String] -> [String] -> Integer -> Integer -> Object makeBasicClaferObject ident' uid' super' reference' cardMin cardMax =- mconcat [ row "ident" ident',- row "uid" uid',+ mconcat [ "ident" .= ident',+ "uid" .= uid', superRow, refRow,- row "cardMin" cardMin,- row "cardMax" cardMax ]+ "cardMin" .= cardMin,+ "cardMax" .= cardMax ] where superRow = case super' of- [s] -> row "super" s+ [s] -> "super" .= s _ -> mempty refRow = case reference' of- [r] -> row "reference" r+ [r] -> "reference" .= r _ -> mempty addIntValue :: Int -> Object -> Object addIntValue value claferObject =- claferObject `mappend` row "value" value+ claferObject `mappend` ("value" .= value) addStringValue :: String -> Object -> Object addStringValue value claferObject =- claferObject `mappend` row "value" value+ claferObject `mappend` ("value" .= value) addElements :: [ Object ] -> Object -> Object addElements elements' claferObject =@@ -90,4 +96,4 @@ constructElements :: [ Object ] -> Object constructElements elements' =- row "elements" $ mconcat $ map element elements'+ pair "elements" $ list pairs elements'
src/Language/Clafer/IG/Process.hs view
@@ -37,11 +37,11 @@ executableDirectory = fst `liftM` splitExecutablePath --- | Start another process and return the piped std_in, std_out stream-pipeProcess :: FilePath -> [String] -> IO Process-pipeProcess exec args =+-- | Start another process with the given environment and return the piped std_in, std_out stream+pipeProcess :: FilePath -> [String] -> [(String, String)] -> IO Process+pipeProcess exec args environment = do- let process = (proc exec args) { std_in = CreatePipe, std_out = CreatePipe }+ let process = (proc exec args) { std_in = CreatePipe, std_out = CreatePipe, env = Just environment } (Just stdIn', Just stdOut', _, proceHandle) <- createProcess process hSetNewlineMode stdIn' noNewlineTranslation return $ Process stdIn' stdOut' proceHandle -- Pipe always has a handle according to docs
src/Language/Clafer/IG/Solution.hs view
@@ -20,7 +20,7 @@ SOFTWARE. -} -module Language.Clafer.IG.Solution (Solution(..), Sig(..), Atom(..), Field(..), Tuple(..), parseSolution) where+module Language.Clafer.IG.Solution (Solution(..), Sig(..), Atom(..), Field(..), Tuple(..), parseSolution, parseTrace) where import Control.Monad import Data.Maybe@@ -53,6 +53,26 @@ fields = map parseField $ fieldElems rootElem in Solution sigs fields+++-- | The states of a trace of a dynamic model, one instance each, and the state to which+-- its last state loops back: Alloy gives the length of the trace and of its loop.+parseTrace :: String -> ([Solution], Int)+parseTrace xml =+ let (Document _ _ root _) = xmlParse "claferIG" xml+ instances = (tag "alloy" /> tag "instance") $ CElem root noPos++ parseInstance instance' = Solution+ (map parseSig $ (keep /> tag "sig") instance')+ (map parseField $ (keep /> tag "field") instance')++ loopState = fromMaybe 0 $ do+ instance' <- listToMaybe instances+ traceLength <- read <$> findOptAttr "tracelength" instance'+ loopLength <- read <$> findOptAttr "looplength" instance'+ return $ traceLength - loopLength+ in+ (map parseInstance instances, loopState) parseSig :: Content i -> Sig
+ src/Language/Clafer/IG/SolutionView.hs view
@@ -0,0 +1,213 @@+{-+ Copyright (C) 2026 Michal Antkiewicz <http://gsd.uwaterloo.ca>++ Permission is hereby granted, free of charge, to any person obtaining a copy of+ this software and associated documentation files (the "Software"), to deal in+ the Software without restriction, including without limitation the rights to+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies+ of the Software, and to permit persons to whom the Software is furnished to do+ so, subject to the following conditions:++ The above copyright notice and this permission notice shall be included in all+ copies or substantial portions of the Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWARE.+-}+-- | The views of the solutions: a static model has instances, and a dynamic model has traces,+-- whose states are instances. Both are sequences of snapshots, which the full view shows+-- one by one, and the diff view shows as the changes from the previous snapshot.+module Language.Clafer.IG.SolutionView (showSolution, showSolutionDiff, solutionText, solutionJSON, solutionDot, solutionDiffDot, lpqName) where++import Data.Char (isDigit)+import Data.List+import Language.Clafer.Common (UIDIClaferMap)+import Language.Clafer.QNameUID (QNameMaps, getLPQName)+import Language.Clafer.IG.ClaferModel+import Language.Clafer.IG.JSONGenerator (generateJSON)+import Prelude hiding (id)++-- | The full view of the n-th solution: the instance, or each state of the trace+showSolution :: Int -> ClaferSolution -> String+showSolution n (ClaferInstance model) =+ "=== Instance " ++ show n ++ " Begin ===\n\n" +++ show model +++ "\n--- Instance " ++ show n ++ " End ---\n\n"+showSolution n (ClaferTrace states loopState) =+ "=== Trace " ++ show n ++ " Begin ===\n\n" +++ solutionText (ClaferTrace states loopState) +++ "--- Trace " ++ show n ++ " End ---\n\n"++-- | The text of a solution, as it is saved: the instance, or the states of the trace+solutionText :: ClaferSolution -> String+solutionText (ClaferInstance model) = show model+solutionText (ClaferTrace states loopState) =+ concat (zipWith showState [0 :: Int ..] states) ++ loopBack loopState+ where+ showState i state = stateHeader i ++ show state ++ "\n"++-- | The diff view of the n-th solution. The first state of a trace, whose clafers all appear (+),+-- is shown in full, and each next state as its changes: the clafers that appear (+), with their children, and that+-- disappear (-), and the values that change (~), each at its depth in the tree and with its+-- least-partially-qualified name, given by the UID of its clafer. The states are compared by+-- instance, which has the same name in every state. An instance is compared with the previous+-- instance, if any, by its structure, since the names of the instances of separate solutions+-- are unrelated.+showSolutionDiff :: (String -> String) -> Int -> Maybe ClaferSolution -> ClaferSolution -> String+showSolutionDiff names n (Just (ClaferInstance previous)) (ClaferInstance model) =+ "=== Instance " ++ show n ++ " Begin ===\n\n" +++ showChanges (structureDiff names previous model) +++ "\n--- Instance " ++ show n ++ " End ---\n\n"+showSolutionDiff _ n _ (ClaferInstance model) =+ "=== Instance " ++ show n ++ " Begin ===\n\n" +++ appears model +++ "\n--- Instance " ++ show n ++ " End ---\n\n"+showSolutionDiff names n _ (ClaferTrace states loopState) =+ "=== Trace " ++ show n ++ " Begin ===\n\n" +++ concat (zipWith3 showState [0 :: Int ..] (Nothing : map Just states) states) +++ loopBack loopState +++ "--- Trace " ++ show n ++ " End ---\n\n"+ where+ showState i Nothing state = stateHeader i ++ appears state ++ "\n"+ showState i (Just previous) state = stateHeader i ++ showChanges (instanceDiff names previous state) ++ "\n"++-- | A snapshot without a previous one, whose clafers all appear (+), aligned with the changes+appears :: ClaferModel -> String+appears = unlines . map ("+ " ++) . lines . show++-- | The least-partially-qualified name of a clafer, with dots, e.g., normal.green, or its UID+lpqName :: QNameMaps -> String -> String+lpqName qNameMaps' uid' = maybe uid' (dropWhile (== '.') . dotted) $ getLPQName qNameMaps' uid'+ where+ dotted (':' : ':' : rest) = '.' : dotted rest+ dotted (c : rest) = c : dotted rest+ dotted [] = []++-- | The JSON of a solution: the instance, or the states of the trace and its loop state+solutionJSON :: UIDIClaferMap -> ClaferSolution -> String+solutionJSON uidIClaferMap' (ClaferInstance model) = generateJSON uidIClaferMap' model+solutionJSON uidIClaferMap' (ClaferTrace states loopState) =+ "{\"states\": [" ++ intercalate ", " (map (generateJSON uidIClaferMap') states) ++ "], \"loop\": " ++ show loopState ++ "}"++-- | The Graphviz graph of a solution: an instance is a single node, and a trace is a node per state+-- with an edge to the next state, and a dashed edge from the last state back to the loop state.+solutionDot :: ClaferSolution -> String+solutionDot solution = graphWith (map show $ solutionModels solution) solution++-- | The Graphviz graph of a solution in the diff view, which keeps large traces readable: the first+-- state in full, and each next state as its changes from the previous one.+solutionDiffDot :: (String -> String) -> ClaferSolution -> String+solutionDiffDot names solution@(ClaferTrace states _) =+ graphWith labels solution+ where+ labels = appears (head states) : zipWith (\previous state -> showChanges (instanceDiff names previous state)) states (tail states)+solutionDiffDot _ solution = solutionDot solution++-- | The graph of a solution, given the label of the instance, or of each state+graphWith :: [String] -> ClaferSolution -> String+graphWith labels solution =+ -- no minimum size, so that a box fits its text+ "digraph solution {\n node [shape=box, fontname=\"monospace\", width=0, height=0, margin=\"0.08,0.04\"];\n" ++ body solution ++ "}\n"+ where+ body (ClaferInstance _) = dotNode "instance" "" (concat labels)+ body (ClaferTrace states loopState) =+ " start [shape=point, width=0.05];\n" +++ concat (zipWith showState [0 ..] labels) +++ " start -> " ++ stateNode 0 ++ ";\n" +++ concatMap showEdge [1 .. lastState] +++ " " ++ stateNode lastState ++ " -> " ++ stateNode loopState ++ " [style=dashed, label=\"loop\"];\n"+ where+ lastState = length states - 1+ -- the name of a state is outside its box, and it is also the tooltip of the box+ showState i label = dotNode (stateNode i) (", xlabel=\"" ++ stateNode i ++ "\"") label+ showEdge i = " " ++ stateNode (i - 1) ++ " -> " ++ stateNode i ++ ";\n"+ stateNode i = "S" ++ show (i :: Int)++-- | A node with left-aligned lines, which keep the indentation of the tree, and further attributes+dotNode :: String -> String -> String -> String+dotNode name attributes text = " " ++ name ++ " [label=\"" ++ concatMap line (filter (not . null) $ lines text) ++ "\"" ++ attributes ++ "];\n"+ where+ line l = concatMap escape l ++ "\\l"+ escape '"' = "\\\""+ escape '\\' = "\\\\"+ escape c = [c]++stateHeader :: Int -> String+stateHeader i = "--- State " ++ show i ++ " ---\n"++loopBack :: Int -> String+loopBack loopState = "--- Loop back to state " ++ show loopState ++ " ---\n\n"++-- | A clafer of an instance: the names on the path from a top-level clafer to it, which identify+-- it, its name to show and its value+data Entry = Entry {e_path :: [String], e_name :: String, e_value :: String} deriving (Eq, Ord)++entries :: (String -> String) -> ClaferModel -> [Entry]+entries names (ClaferModel topLevelClafers) = concatMap (entries' []) topLevelClafers+ where+ entries' path clafer@(Clafer id _ value children) =+ Entry path' (displayName clafer) (maybe "" showValue value) : concatMap (entries' path') children+ where+ path' = path ++ [i_name id]+ showValue (AliasValue alias) = " -> " ++ i_name alias+ showValue (IntValue v) = " -> " ++ show v+ showValue (StringValue v) = " -> " ++ v+ -- the instance's name with the least-partially-qualified name of its clafer: green$2 : Light+ -- -> normal.green$2 : Light+ displayName (Clafer id uid' _ _) =+ case stripPrefix (lastSegment lpq) (i_name id) of+ Just rest -> lpq ++ rest+ Nothing -> i_name id+ where+ lpq = names uid'+ lastSegment = reverse . takeWhile (/= '.') . reverse++data Change = Added Entry | Removed Entry | Changed Entry++-- | The changes, each as in the tree of the instance, after its marker+showChanges :: [Change] -> String+showChanges [] = "(no changes)\n"+showChanges changes = concatMap showChange changes+ where+ showChange (Added e) = line '+' e+ showChange (Removed e) = line '-' e+ showChange (Changed e) = line '~' e+ line marker (Entry path name value) = marker : ' ' : replicate (2 * (length path - 1)) ' ' ++ name ++ value ++ "\n"++-- | The changes from one state to the next: an instance is the same in both if it has the same+-- path. A removed clafer is shown without its children, which disappear with it.+instanceDiff :: (String -> String) -> ClaferModel -> ClaferModel -> [Change]+instanceDiff names previous current =+ [Removed e | e <- before, e_path e `notElem` currentPaths, not $ any (`elem` removedPaths) (properPrefixes $ e_path e)] +++ [Changed e | e <- after, Just v <- [lookup (e_path e) previousValues], v /= e_value e] +++ [Added e | e <- after, e_path e `notElem` previousPaths]+ where+ before = entries names previous+ after = entries names current+ previousPaths = map e_path before+ currentPaths = map e_path after+ previousValues = [(e_path e, e_value e) | e <- before]+ removedPaths = filter (`notElem` currentPaths) previousPaths++-- | The changes from one instance to another of a static model, by their structure: the clafers+-- without the numbers of their instances, with their values, as multisets.+structureDiff :: (String -> String) -> ClaferModel -> ClaferModel -> [Change]+structureDiff names previous current =+ map Removed (sort $ before \\ after) ++ map Added (sort $ after \\ before)+ where+ before = map anonymous $ entries names previous+ after = map anonymous $ entries names current+ anonymous (Entry path name value) = Entry (map dropOrdinal path) (dropOrdinal name) (dropOrdinal value)+ -- name$2 : Super -> name : Super+ dropOrdinal name = case break (== '$') name of+ (prefix, '$' : rest) -> prefix ++ dropWhile isDigit rest+ _ -> name++-- | The paths of the ancestors, the outermost first+properPrefixes :: [a] -> [[a]]+properPrefixes xs = take (length xs - 1) $ drop 1 $ inits xs
src/Language/Clafer/IG/Sugarer.hs view
@@ -20,11 +20,12 @@ SOFTWARE. -} -module Language.Clafer.IG.Sugarer (sugarClaferModel) where+module Language.Clafer.IG.Sugarer (sugarClaferModel, sugarClaferStates) where import Language.Clafer.Common+import Language.Clafer.Intermediate.Intclafer (_ident) import Language.Clafer.IG.ClaferModel-import Data.Maybe (fromJust)+import Data.Maybe (fromMaybe, fromJust) import Data.List as List hiding (map) import Data.Map as Map hiding (map, foldr, foldl) import Prelude hiding (id)@@ -39,47 +40,67 @@ -- | Adds the full name to the census-poll :: Id -> Census -> Census-poll id (Census sample' counts') =+poll :: UIDIClaferMap -> Id -> Census -> Census+poll uidIClaferMap' id (Census sample' counts') = Census sample'' counts'' where fullName = i_name id- name = makeSimpleName fullName+ name = claferName uidIClaferMap' fullName counts'' = insertWith (+) name 1 counts' ordinal' = findWithDefault (error $ "Did not find " ++ name ++ " in counts.") name counts'' sample'' = insertWith (error $ "Polled " ++ fullName ++ " twice in the census.") id (ordinal', name) sample' --- Transforms c2_name -> name-makeSimpleName :: String -> String-makeSimpleName name' = case dropWhile (/='_') name' of- "" -> error "Unexpected Clafer name " ++ name'- x -> tail x+-- | The clafer's name for its UID (its Alloy name): its _ident, which the UID need not+-- contain, e.g., size for x__size, or a' for a_prime.+claferName :: UIDIClaferMap -> String -> String+claferName uidIClaferMap' uid = maybe uid _ident $ findIClafer uidIClaferMap' uid -- | Count the number of each clafer-claferModelCensus :: ClaferModel -> Census-claferModelCensus (ClaferModel topLevelClafers) =- clafersCensus (Census Map.empty Map.empty) topLevelClafers+claferModelCensus :: UIDIClaferMap -> ClaferModel -> Census+claferModelCensus uidIClaferMap' = statesCensus uidIClaferMap' . (:[])++-- | Count the number of each clafer in the states of a trace: an instance that exists in+-- several states is counted once, so it has the same name in each of them+statesCensus :: UIDIClaferMap -> [ClaferModel] -> Census+statesCensus uidIClaferMap' states =+ foldl clafersCensus (Census Map.empty Map.empty) $ map c_topLevel states where clafersCensus = foldl claferCensus- claferCensus census Clafer{c_id=id, c_children=children} = poll id (clafersCensus census children)+ claferCensus census Clafer{c_id=id, c_children=children} = pollOnce id (clafersCensus census children)+ pollOnce id census@(Census sample' _)+ | id `member` sample' = census+ | otherwise = poll uidIClaferMap' id census -- | Rewrite the model into a human-friendlier format-sugarClaferModel:: Bool -> Bool -> UIDIClaferMap -> ClaferModel -> (Map Int String) -> ClaferModel-sugarClaferModel useUids addTypes uidIClaferMap' model@(ClaferModel topLevelClafers) sMap =+sugarClaferModel:: (String -> String) -> Bool -> Bool -> UIDIClaferMap -> ClaferModel -> Map Int String -> ClaferModel+sugarClaferModel toUid useUids addTypes uidIClaferMap' model sMap =+ sugarWithCensus (claferModelCensus uidIClaferMap' model) toUid useUids addTypes uidIClaferMap' model sMap++-- | Rewrite the states of a trace into a human-friendlier format: an instance has the same name+-- in every state+sugarClaferStates :: (String -> String) -> Bool -> Bool -> UIDIClaferMap -> [ClaferModel] -> Map Int String -> [ClaferModel]+sugarClaferStates toUid useUids addTypes uidIClaferMap' states sMap =+ map (\state -> sugarWithCensus census toUid useUids addTypes uidIClaferMap' state sMap) states+ where+ census = statesCensus uidIClaferMap' states++-- | The clafers of the model are by their Alloy names; with useUids, they are shown by their UIDs (toUid).+sugarWithCensus :: Census -> (String -> String) -> Bool -> Bool -> UIDIClaferMap -> ClaferModel -> Map Int String -> ClaferModel+sugarWithCensus census toUid useUids addTypes uidIClaferMap' (ClaferModel topLevelClafers) sMap = ClaferModel $ map sugarClafer topLevelClafers where- sugarClafer (Clafer id value children) =- Clafer (sugarId useUids addTypes True id) (sugarValue (Clafer id value children)) (map sugarClafer children)+ sugarClafer clafer@(Clafer id uid' _ children) =+ Clafer (sugarId useUids addTypes True id) uid' (sugarValue clafer) (map sugarClafer children) - sugarValue (Clafer _ (Just (AliasValue alias)) _) = Just $ AliasValue $ sugarId useUids addTypes False alias- sugarValue (Clafer _ Nothing _) = Nothing- sugarValue c = if (cType c) == "string" then (Just ((StringValue) (getString c))) else (c_value c)+ sugarValue (Clafer _ _ (Just (AliasValue alias)) _) = Just $ AliasValue $ sugarId useUids addTypes False alias+ sugarValue (Clafer _ _ Nothing _) = Nothing+ sugarValue c = if cType c == "string" then Just (StringValue (getString c)) else c_value c - cType (Clafer id _ _) = cTypeSolve $ getReference iclafer+ cType (Clafer id _ _ _) = cTypeSolve $ getReference iclafer where- iclafer = fromJust $ findIClafer uidIClaferMap' $ i_name id+ iclafer = fromMaybe (error $ "IClafer not found:" ++ i_name id) $ findIClafer uidIClaferMap' $ i_name id cTypeSolve ["string"] = "string" cTypeSolve ["integer"] = "integer"@@ -87,41 +108,41 @@ cTypeSolve ["real"] = "real" cTypeSolve _ = "" - getString c = case (Map.lookup strNumber sMap) of+ getString c = case Map.lookup strNumber sMap of Nothing -> "\"<text " ++ show strNumber ++ ">\"" Just s -> s where strNumber = v_value $ fromJust $ c_value c - Census sample' counts' = claferModelCensus model+ Census sample' counts' = census sugarId :: Bool -> Bool -> Bool -> Id -> Id sugarId useUids' addTypes' addRefDecl id =- Id (finalName ++ ordinalDisplay ++ (refDecl addTypes' addRefDecl uidIClaferMap')) 0+ Id (finalName ++ ordinalDisplay ++ refDecl addTypes' addRefDecl uidIClaferMap') 0 where fullName = i_name id- ordinalDisplay = if (useUids || count > 1)+ ordinalDisplay = if useUids || count > 1 then "$" ++ show ordinal else "" refDecl :: Bool -> Bool -> UIDIClaferMap -> String- refDecl True True uidIClaferMap'' = retrieveSuper useUids' uidIClaferMap'' $ i_name id+ refDecl True True uidIClaferMap'' = retrieveSuper toUid useUids' uidIClaferMap'' $ i_name id refDecl _ _ _ = "" (ordinal, simpleName) = findWithDefault (error $ "Sample lookup " ++ show id ++ " failed.") id sample' count = findWithDefault (error $ "Count lookup " ++ simpleName ++ " failed.") simpleName counts'- finalName = if useUids' then fullName else simpleName+ finalName = if useUids' then toUid fullName else simpleName -retrieveSuper :: Bool -> UIDIClaferMap -> String -> String-retrieveSuper useUids' uidIClaferMap' uid =+retrieveSuper :: (String -> String) -> Bool -> UIDIClaferMap -> String -> String+retrieveSuper toUid useUids' uidIClaferMap' uid = sugarSuper (getSuper iclafer) -- ++ -- sugarReference (getReference iclafer) where- iclafer = fromJust $ findIClafer uidIClaferMap' uid+ iclafer = fromMaybe (error $ "IClafer not found: " ++ uid) $ findIClafer uidIClaferMap' uid sugarSuper :: [String] -> String- sugarSuper [s] = " : " ++ if useUids' then s else makeSimpleName s+ sugarSuper [s] = " : " ++ if useUids' then toUid s else claferName uidIClaferMap' s sugarSuper _ = "" -- sugarReference :: [String] -> String -- sugarReference [s] = " -> " ++ s
stack.yaml view
@@ -1,11 +1,19 @@-# for GHC-8.0.2-extra-deps:- - data-stringmap-1.0.1.1- - json-builder-0.3- - HaXml-1.25.3- # - HaXml-1.24 # for Windows-resolver: lts-8.5+# for GHC-9.12.4+resolver: nightly-2026-11-11 +flags:+ # The test suites that need the models in the repositories (and Alloy for claferIG).+ clafer:+ model-tests: true+ claferIG:+ model-tests: true+ packages: - '../clafer' - '.'++# GHC compiles the modules of a package on 8 threads, which takes a third less time than one+# thread; 16 threads are not faster.+# (build: semaphore: true, GHC's -jsem, fails with Stack 3.11.1: "semOpen: does not exist".)+ghc-options:+ "$everything": -j8
+ test/model-tests.hs view
@@ -0,0 +1,659 @@+{-# LANGUAGE TemplateHaskell #-}+{-+ Copyright (C) 2012-2017 Luke Brown <http://gsd.uwaterloo.ca>++ Permission is hereby granted, free of charge, to any person obtaining a copy of+ this software and associated documentation files (the "Software"), to deal in+ the Software without restriction, including without limitation the rights to+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies+ of the Software, and to permit persons to whom the Software is furnished to do+ so, subject to the following conditions:++ The above copyright notice and this permission notice shall be included in all+ copies or substantial portions of the Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWARE.+ -}+-- Generates instances of the models in test/positive with Alloy. Built only with+-- the model-tests flag, in a checkout of the repository: it needs the models, and+-- alloyIG.jar and alloy6.2.0.jar next to the test executable (see `make test`).+import Language.Clafer.IG.ClaferIG+import Language.Clafer.IG.ClaferModel+import Language.Clafer.IG.CommandLine+import Language.Clafer.IG.SolutionView+import Control.Concurrent (threadDelay)+import Control.Monad+import Control.Monad.IO.Class+import Data.List (isInfixOf, isPrefixOf, isSuffixOf)+import Language.Clafer.IG.Constraints+import Language.Clafer.ClaferArgs (ScopeStrategy(..))+import qualified Data.Map as Map+import Data.Maybe+import Data.IORef+import System.Directory+import System.FilePath+import System.Console.CmdArgs+import Prelude hiding (all)+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.TH++tg_modeltests :: TestTree+tg_modeltests = $(testGroupGenerator)++-- | The tests run in parallel, on 8 cores (the executable runs with +RTS -N8): each test has a+-- folder of its own, and the long ones are split into parts.+main :: IO ()+main = defaultMain $ testGroup "Model tests" [ tg_modeltests, lifetimes, patternScopes, finalTarget ]++-- | A new folder for the models of a test, under the temporary directory.+testDir :: String -> IO FilePath+testDir name = do+ dir <- (</> ("claferIG-test-" ++ name)) <$> getTemporaryDirectory+ createDirectoryIfMissing True dir+ return dir++claferIGArgsDef :: IGArgs+claferIGArgsDef = IGArgs {+ all = def,+ maxInstances = def,+ saveDir = def,+ claferModelFile = def,+ imports_comp = def,+ import_root_comp = def,+ public_imports_comp = False,+ import_base_comp = def,+ alloySolution = def,+ bitwidth = 4,+ maxInt = 7,+ useUids = False,+ addTypes = False,+ json = False,+ diff = False,+ dot = False,+ tl_comp = def,+ flatten_inheritance_comp = False,+ no_layout_comp = False,+ check_duplicates_comp = False,+ skip_resolver_comp = False,+ scope_strategy_comp = def+} &= summary claferIGVersion+++defaultIGArgs :: FilePath -> IGArgs+--defaultIGArgs fPath = IGArgs Nothing Nothing fPath False 4 False False False+defaultIGArgs fPath = claferIGArgsDef{claferModelFile = fPath}++--getModel :: MonadIO m => FilePath -> ClaferIGT m (Either Language.ClaferT.ClaferErrs Instance)+getModel fPath = runClaferIGT (defaultIGArgs fPath) $ do+ setGlobalScope (fromMaybe 1 $ all $ defaultIGArgs fPath)+ solve+ counterRef <- liftIO $ newIORef 1+ let saveDirectory = fromMaybe return $ underDirectory `liftM` saveDir (defaultIGArgs fPath)+ let nextFile = savePath fPath counterRef >>= saveDirectory+ file <- liftIO nextFile+ liftIO $ createDirectoryIfMissing True $ takeDirectory file+ next+ where+ savePath :: FilePath -> IORef Int -> IO FilePath+ savePath fPath' counterRef =+ do+ counter <- readIORef counterRef+ writeIORef counterRef (counter + 1)+ return $ fPath' ++ "." ++ (show counter) ++ ".data"+ underDirectory :: FilePath -> FilePath -> IO FilePath+ underDirectory dir file =+ do+ createDirectoryIfMissing True dir+ return $ joinPath [dir, file]+++fromRight (Right x) = x+fromRight _ = error "fromRight received Left _. Should never happen."++-- | The instance, or the first state of the trace+firstModel :: Instance -> ClaferModel+firstModel = head . solutionModels . modelSolution++-- | A traffic light, whose scenario is a trace of a dynamic model+trafficLight :: String+trafficLight = unlines+ [ "abstract xor TrafficLight"+ , " initial xor on -->> off"+ , " initial xor normal"+ , " initial green --> yellow"+ , " yellow --> red"+ , " red --> green"+ , " xor flashing -->> normal"+ , " initial yellow_on --> yellow_off"+ , " yellow_off --> yellow_on"+ , " off --> on"+ , "tl : TrafficLight"+ ]++-- | The solutions of a dynamic model are traces: the scenario gives the states of its trace, and+-- the diff view shows the changes from one state to the next.+case_DynamicModelTrace :: Assertion+case_DynamicModelTrace = do+ dir <- testDir "DynamicModelTrace"+ writeFile (dir </> "scenario.cfr") $ trafficLight ++ " [ initially (green --> yellow --> red --> green --> yellow_on --> yellow_off --> off) ]\n"+ result <- getModel $ dir </> "scenario.cfr"+ case modelSolution $ fromRight result of+ ClaferTrace states _ -> do+ length states >= 7 @? ("The trace has the 7 states of the scenario: " ++ show (length states))+ let leaves = map (map c_name . filter (null . c_children) . traverseModel) states+ take 7 leaves == [["green"], ["yellow"], ["red"], ["green"], ["yellow_on"], ["yellow_off"], ["off"]]+ @? ("The states follow the scenario: " ++ show leaves)+ let diffView = showSolutionDiff id 1 Nothing (ClaferTrace states 0)+ ("- green\n+ yellow" `isInfixOf` diffView) @? ("The diff view shows the change of the light: " ++ diffView)+ ClaferInstance _ -> assertFailure "A dynamic model has traces"++-- | The graph of a trace has its states, their transitions and the loop; of an instance, a node.+case_SolutionGraph :: Assertion+case_SolutionGraph = do+ dir <- testDir "SolutionGraph"+ writeFile (dir </> "graph.cfr") trafficLight+ result <- runClaferIGT (defaultIGArgs $ dir </> "graph.cfr") $ solve >> next+ case fromRight result of+ Instance solution@(ClaferTrace states loopState) _ -> do+ let+ graph = solutionDot solution+ lastState = length states - 1+ has line = (line `isInfixOf` graph) @? ("The graph has " ++ line ++ ": " ++ graph)+ has "start -> S0;"+ forM_ [1 .. lastState] $ \i -> has $ "S" ++ show (i - 1) ++ " -> S" ++ show i ++ ";"+ has $ "S" ++ show lastState ++ " -> S" ++ show loopState ++ " [style=dashed"+ has "xlabel=\"S0\""+ (not ("State" `isInfixOf` graph)) @? ("The states have no header: " ++ graph)+ let+ diffGraph = solutionDiffDot id solution+ diffHas line = (line `isInfixOf` diffGraph) @? ("The diff graph has " ++ line ++ ": " ++ diffGraph)+ diffHas "S0 [label=\"+ "+ diffHas "S1 [label=\""+ diffHas $ "S" ++ show lastState ++ " -> S" ++ show loopState ++ " [style=dashed"+ diffHas "[label=\"- "+ _ -> assertFailure "A trace"+ let+ value = Clafer (Id "c" 0) "c" (Just $ StringValue "\"a\"") []+ graph = solutionDot $ ClaferInstance $ ClaferModel [value]+ ("\\\"a\\\"" `isInfixOf` graph) @? ("The quotes are escaped: " ++ graph)++-- | Each assertion, also a nested one or one on the line of another, is checked within the scopes:+-- a failed one has a counterexample, which leaves the next solution as it is.+case_Assertions :: Assertion+case_Assertions = do+ dir <- testDir "Assertions"+ writeFile (dir </> "dynamic.cfr") $ unlines+ [ "xor s"+ , " initial a --> b"+ , " b --> a"+ , " assert [ a => X b ]"+ , "assert [ never s.b ] assert [ s.a => X s.a ]" ]+ writeFile (dir </> "static.cfr") $ unlines+ [ "abstract P"+ , " age -> integer"+ , " [ age >= 0 ]"+ , " assert [ age >= 0 ]"+ , " assert [ age >= 3 ]"+ , "x : P" ]+ let+ results file = do+ result <- runClaferIGT (defaultIGArgs $ dir </> file) $ do+ solve+ _ <- next+ assertions <- getAssertions+ checks <- forM assertions $ \(name, info) -> ((,) (syntax info) . isJust) <$> checkAssertion name+ solution <- next+ return (checks, solution)+ return $ fromRight result+ (dynamic, _) <- results "dynamic.cfr"+ dynamic @?= [("a => X b", False), ("never s.b", True), ("s.a => X s.a", True)]+ (static, solution) <- results "static.cfr"+ static @?= [("age >= 0", False), ("age >= 3", True)]+ onLine <- runClaferIGT (defaultIGArgs $ dir </> "static.cfr") $ do+ solve+ assertions <- getAssertions+ return $ map (\n -> map (syntax . snd) $ filter (isOnLine n . snd) assertions) [4, 5, 6]+ fromRight onLine @?= [["age >= 0"], ["age >= 3"], []]+ case solution of+ Instance{} -> return ()+ _ -> assertFailure "The next solution stays as it is"++-- | The assertions with whether they hold, and whether the model has a solution, with the scope+-- strategy, the global scope and the maximum trace length.+checkLifetimes :: FilePath -> String -> ScopeStrategy -> Integer -> Integer -> IO ([(String, Bool)], Bool)+checkLifetimes dir model strategy scope traceLength = do+ writeFile (dir </> "lifetimes.cfr") model+ result <- runClaferIGT (defaultIGArgs $ dir </> "lifetimes.cfr"){scope_strategy_comp = strategy} $ do+ -- as the command i does: the clafers have scopes, which the global scope does not change+ getScopes >>= mapM_ (\s -> (fmap (max scope) . valueOfScope) (fst s) >>= \n -> setScope n s)+ setGlobalScope scope+ setMaxTraceLength traceLength+ solve+ solution <- next+ assertions <- getAssertions+ holds <- forM assertions $ \(name', info') -> ((,) (syntax info') . isNothing) <$> checkAssertion name'+ return (holds, case solution of+ Instance{} -> True+ _ -> False)+ return $ fromRight result++-- | A clafer whose UID cannot be an Alloy name, e.g., sig, has a sig of its own, this/sig_1, and so+-- does r_x next to x (r_x is the relation of x); claferIG translates between the UIDs and the+-- sigs, and shows the clafers by their names.+case_AlloyNamesOfUIDs :: Assertion+case_AlloyNamesOfUIDs = do+ dir <- testDir "AlloyNamesOfUIDs"+ writeFile (dir </> "names.cfr") $ unlines [ "sig", "x", "r_x ?" ]+ result <- runClaferIGT (defaultIGArgs $ dir </> "names.cfr") $ do+ sigs <- map fst <$> getScopes+ sigOfSig <- sigOfUID "sig"+ sigOfRx <- sigOfUID "r_x"+ sigOfX <- sigOfUID "x"+ uid' <- uidOfSig "this/sig_1"+ name' <- claferNameOfSig "this/sig_1"+ return (sigs, [sigOfSig, sigOfRx, sigOfX], uid', name')+ let (sigs, mapped, uid', name') = fromRight result+ mapped @?= ["this/sig_1", "this/r_x_1", "this/x"]+ and [ m `elem` sigs | m <- mapped ] @? ("The sigs are not those of the Alloy model: " ++ show sigs)+ uid' @?= "sig"+ name' @?= "sig"++-- | An abstract clafer that no concrete clafer inherits from, and the clafers in it, have no+-- instances: their scopes stay 0 when the scopes are raised. An abstract clafer that a concrete+-- clafer inherits from through another abstract clafer keeps its scope.+case_EmptyAbstractScopes :: Assertion+case_EmptyAbstractScopes = do+ dir <- testDir "EmptyAbstractScopes"+ writeFile (dir </> "empty.cfr") $ unlines+ [ "abstract A", " x ?", "abstract B : A", "abstract E", " y ?", "C : B" ]+ result <- runClaferIGT (defaultIGArgs $ dir </> "empty.cfr") $ do+ initial <- getScopes+ getScopes >>= mapM_ (increaseScope 2)+ mapM_ (setAlloyScope 4) ["this/E", "this/y"]+ raised <- getScopes+ return (initial, raised)+ let (initial, raised) = fromRight result+ [ lookup ("this/" ++ s) initial | s <- ["A", "B", "E", "y"] ] @?= [Just 1, Just 1, Just 0, Just 0]+ [ lookup ("this/" ++ s) raised | s <- ["A", "B", "C", "E", "y"] ] @?= [Just 3, Just 3, Just 3, Just 0, Just 0]++-- | The obligations of a constraint last while the parent of its context instance exists, also+-- when they are negated; a scope bounds the instance identities across the trace, and an+-- instance keeps its parent. Checked with both scope strategies, at scopes 1 to 3 and up to+-- 3 and 10 states.+lifetimes :: TestTree+lifetimes = testGroup "Lifetimes"+ [ testCase (show s ++ ", scope " ++ show n ++ ", " ++ show l ++ " states") $ lifetimesAt s n l+ | s <- [None, Simple], n <- [1, 2, 3], l <- [3, 10] ]++lifetimesAt :: ScopeStrategy -> Integer -> Integer -> Assertion+lifetimesAt strategy scope traceLength = do+ dir <- testDir $ "Lifetimes-" ++ show strategy ++ "-" ++ show scope ++ "-" ++ show traceLength+ let+ machine final' = unlines+ [ "go ?"+ , final' ++ "xor sm"+ , " initial a"+ , " [ go --> b ]"+ , " b"+ , " c"+ , "assert [ all m : sm | m.a && go => X (m.b || no (m ** sm)) ]"+ , "assert [ sm.a && go => X sm.b ]" ]+ negated constraints' = unlines $+ [ "machine ?"+ , " ctx"+ , " error ?" ] ++ map (" " ++) constraints' +++ [ "[ initially machine ]"+ , "[ initially (X no machine) ]" ]+ scopeIdentities = "item\n[ initially (all x : item | X no (x ** item)) ]\n"+ parentAcrossLifetimes = unlines+ [ "box 2"+ , " item ?"+ , "[ initially (some box.item) ]"+ , "[ initially (all i : box.item | X (no (i ** box.item) && X some (i ** box.item))) ]"+ , "assert [ all b : box | all i : b.item | G (some (i ** box.item) => some (i ** b.item)) ]" ]+ persistent = unlines+ [ "final machine"+ , " ctx"+ , " error ?"+ , " [ F error ]"+ , " [ !(F error) ]" ]+ holds = map snd+ at = " (" ++ show strategy ++ ", scope " ++ show scope ++ ", " ++ show traceLength ++ " states)"+ check = checkLifetimes dir+ do+ -- a transition in its source state leads to b while the machine exists+ (final', _) <- check (machine "final ") strategy scope traceLength+ holds final' @?= [True, True]+ -- a replaced machine starts again, and the transition of the old one lapses+ (replaced, _) <- check (machine "") strategy scope traceLength+ holds replaced == [True, scope == 1] @? ("The transition lapses with a replaced machine" ++ at ++ ": " ++ show replaced)+ -- a negated obligation lapses with the parent too+ (equivalences, trace) <- check (negated+ [ "assert [ (G !error) <=> !(F error) ]"+ , "assert [ !(X error) <=> X !error ]"+ , "assert [ !(error U !error) <=> (error W (!error && error)) ]" ]) strategy scope traceLength+ holds equivalences @?= [True, True, True]+ trace @? ("The machine disappears" ++ at)+ (_, globally) <- check (negated ["[ G !error ]"]) strategy scope traceLength+ globally @? ("G !error lets the machine disappear" ++ at)+ (_, notEventually) <- check (negated ["[ !(F error) ]"]) strategy scope traceLength+ notEventually @? ("!(F error) lets the machine disappear" ++ at)+ -- while the parent persists, a formula and its negation contradict each other+ (_, contradiction) <- check persistent strategy scope traceLength+ not contradiction @? ("F error and !(F error) contradict each other while the machine exists" ++ at)+ -- another instance of item in each state needs two identities+ (_, identities) <- check scopeIdentities strategy scope traceLength+ identities == (scope > 1) @? ("A scope bounds the identities across the trace" ++ at)+ (sameParent, _) <- check parentAcrossLifetimes strategy scope traceLength+ holds sameParent @?= [True]++-- | Whether the model has a trace, with the global scope.+hasTrace :: FilePath -> Integer -> String -> IO Bool+hasTrace dir scope model = snd <$> checkLifetimes dir model Simple scope 10++-- | s must follow every p between q and r, not only a p at q; s must precede p from the first q,+-- not from a later q, so at the top level, where a pattern holds in every state, every q starts+-- the scope (kbak/clafer-semantics#127).+patternScopes :: TestTree+patternScopes = testGroup "PatternScopes" $ zipWith test [1 :: Int ..]+ -- q, then p, then r: p needs s before r+ [ (False, follow, "q && !p && !r && !s && X (!q && p && !r && !s && X (!q && !p && !r && !s && X (r && !p && !s)))")+ , (True, follow, "q && !p && !r && !s && X (!q && p && !r && !s && X (!q && !p && !r && s && X (r && !p)))")+ -- q, p, q, s: the second q does not hide the p after the first one+ , (False, precede, "q && !p && !s && X (!q && p && !s && X (q && !p && !s && X (s && !p && !q)))")+ -- q, s, p, q, p: at the top level, the second q needs an s before its p+ , (False, precede, qspqp)+ , (True, "initially (" ++ precede ++ ")", qspqp) ]+ where+ model pattern' scenario = unlines ["q ?", "p ?", "s ?", "r ?", "[ " ++ pattern' ++ " ]", "[ initially (" ++ scenario ++ ") ]"]+ test i (expected, pattern', scenario) = testCase ("[ " ++ pattern' ++ " ] " ++ show i) $ do+ dir <- testDir $ "PatternScopes-" ++ show i+ actual <- hasTrace dir 1 $ model pattern' scenario+ actual == expected @? ("[ " ++ pattern' ++ " ] on " ++ scenario ++ (if expected then " has a trace" else " has no trace"))+ follow = "s must follow p between q and r"+ precede = "s must precede p after q"+ qspqp = "q && !p && !s && X (!q && !p && s && X (!q && p && !s && X (q && !p && !s && X (!q && p && !s))))"++-- | finalref fixes the target of each instance, finaltarget the set of targets of the instances+-- in their parent, so they may swap targets, but a new instance points to an old target; final+-- fixes both (kbak/clafer-semantics#127).+finalTarget :: TestTree+finalTarget = testGroup "FinalTarget"+ [ testCase "its own reference" $ finalTargetOf "own" ("", " -> E")+ , testCase "an inherited reference" $ finalTargetOf "inherited" (" : engine", "")+ , testCase "finaltarget on the abstract clafer" finalTargetAbstract ]++finalTargetModel :: [String] -> String -> String+finalTargetModel clafer' scenario = unlines $+ ["abstract E", "e1 : E", "e2 : E", "abstract Car", " abstract engine -> E", "final car : Car"]+ ++ map (" " ++) clafer' ++ ["[ initially (" ++ scenario ++ ") ]"]++finalTargetSwap, finalTargetReplace :: String+finalTargetSwap = "some x : car.h | x.dref = e1 && X (some (x ** car.h) && x.dref = e2)"+finalTargetReplace = "car.h.dref = e1 && X (car.h.dref = e2)"++finalTargetOf :: String -> (String, String) -> Assertion+finalTargetOf name (super', ref) = do+ dir <- testDir $ "FinalTarget-" ++ name+ let+ swap = finalTargetSwap+ replace = finalTargetReplace+ check expected clafer' scenario = do+ actual <- hasTrace dir 2 $ finalTargetModel clafer' scenario+ actual == expected @? (unwords clafer' ++ ": " ++ scenario ++ (if expected then " has a trace" else " has no trace"))+ h modifier card = [modifier ++ " h" ++ super' ++ ref ++ card]+ do+ check True (h "finaltarget" " 2") swap+ check False (h "finalref" " 2") swap+ check False (h "final" " 2") swap+ check False (h "finaltarget" "") replace+ check True (h "finalref" "") replace+ check True (h "" "") replace+ -- both modifiers, in either order, mean both+ forM_ ["finalref finaltarget", "finaltarget finalref"] $ \both -> do+ check False (h both " 2") swap+ check False (h both "") replace++-- | finaltarget on the abstract clafer fixes the targets of all its instances in the parent.+finalTargetAbstract :: Assertion+finalTargetAbstract = do+ dir <- testDir "FinalTarget-abstract"+ let abstract' clafer' scenario = replace' "abstract engine" "abstract finaltarget engine" $ finalTargetModel clafer' scenario+ replace' old new s = unlines [ if l == " " ++ old ++ " -> E" then " " ++ new ++ " -> E" else l | l <- lines s ]+ hasTrace dir 2 (abstract' ["h : engine 2"] finalTargetSwap) >>= (@? "finaltarget engine: the instances of h swap their targets")+ hasTrace dir 2 (abstract' ["h : engine"] finalTargetReplace) >>= (@? "finaltarget engine: a new h points to an old target") . not++-- | A scenario that contradicts the model has an unsat core with the scenario and the transition+-- it contradicts.+case_DynamicModelUnsatCore :: Assertion+case_DynamicModelUnsatCore = do+ dir <- testDir "DynamicModelUnsatCore"+ writeFile (dir </> "contradiction.cfr") $ trafficLight ++ " [ initially (green --> red) ]\n"+ result <- getModel $ dir </> "contradiction.cfr"+ case fromRight result of+ UnsatCore core _ -> do+ let shown = map show core+ any ("initially (green --> red)" `isInfixOf`) shown @? ("The core has the scenario: " ++ show shown)+ any ("green --> yellow" `isInfixOf`) shown @? ("The core has the transition: " ++ show shown)+ _ -> assertFailure "The scenario contradicts the model"++-- | A fork has the states of the last trace before the given state; a new configuration differs+-- in the clafers that do not change over time.+case_DynamicModelForkAndConfiguration :: Assertion+case_DynamicModelForkAndConfiguration = do+ dir <- testDir "DynamicModelForkAndConfiguration"+ writeFile (dir </> "fork.cfr") trafficLight+ forked <- runClaferIGT (defaultIGArgs $ dir </> "fork.cfr") $ do+ solve+ liftM2 (,) next (fork 2)+ case fromRight forked of+ (Instance (ClaferTrace states _) _, Instance (ClaferTrace states' _) _) ->+ map show (take 2 states) == map show (take 2 states') @? "The fork has the first 2 states of the trace"+ _ -> assertFailure "A trace and its fork"+ writeFile (dir </> "configuration.cfr") $ unlines+ [ "final Features"+ , " final EU ?"+ , "xor Light"+ , " initial red --> green"+ , " green --> red"+ ]+ configurations <- runClaferIGT (defaultIGArgs $ dir </> "configuration.cfr") $ do+ solve+ sequence [next, nextConfiguration, nextConfiguration]+ case fromRight configurations of+ [Instance (ClaferTrace (state : _) _) _, Instance (ClaferTrace (state' : _) _) _, NoInstance] ->+ (("EU" `isInfixOf` show state) /= ("EU" `isInfixOf` show state')) @? "The configurations differ in EU"+ _ -> assertFailure "Two configurations"++-- | Only the first solve logs the translation of the model, to a file kodkod<n>.log in the session's+-- folder, which Kodkod's prover needs for the unsat core of a model without instances. The next+-- trace, a fork and another configuration give no core, so they log nothing. Each of them logged+-- the translation too, which for a large model took gigabytes of the folder, e.g., 11 GB in 3+-- minutes for the next traces of the TLS handshake model.+-- When the session ends, its folder is removed. Alloy removes its own files in it at the same+-- time, and the removal stopped at the first file that was gone, with a NoSuchFileException; the+-- test cannot make that happen, it only checks that the folder is gone.+case_SessionTmpdir :: Assertion+case_SessionTmpdir = do+ dir <- testDir "SessionTmpdir"+ writeFile (dir </> "light.cfr") trafficLight+ result <- runClaferIGT (defaultIGArgs $ dir </> "light.cfr") $ do+ tmpdir <- getSessionTmpdir+ setMaxTraceLength 3+ -- the first trace, of the first solve, which solve only starts+ solve+ _ <- next+ first <- liftIO $ translationLogs tmpdir+ others <- sequence [next, fork 1, nextConfiguration]+ after <- liftIO $ translationLogs tmpdir+ quit+ return (tmpdir, first, others, after)+ let (tmpdir, first, others, after) = fromRight result+ not (null first) @? "The first solve logs the translation"+ [ isInstance o | o <- others ] == [True, True, False] @? ("A next trace and a fork; the traffic light has one configuration: " ++ show [ isInstance o | o <- others ])+ null (filter (`notElem` first) after) @? ("The next trace, the fork and the configuration log no translation: " ++ show (filter (`notElem` first) after))+ removed <- gone tmpdir (100 :: Int)+ removed @? ("The session's folder is removed when the session ends: " ++ tmpdir)+ where+ isInstance Instance{} = True+ isInstance _ = False+ translationLogs tmpdir = filter (\f -> "kodkod" `isPrefixOf` f && ".log" `isSuffixOf` f) <$> listDirectory tmpdir+ -- alloyIG removes the folder when its JVM exits, after the quit command+ gone tmpdir tries = do+ exists <- doesDirectoryExist tmpdir+ if not exists then return True+ else if tries <= 0 then return False+ else threadDelay 100000 >> gone tmpdir (tries - 1)++-- | A static model gives an instance with another structure, regardless of the values.+case_StaticModelConfiguration :: Assertion+case_StaticModelConfiguration = do+ dir <- testDir "StaticModelConfiguration"+ writeFile (dir </> "static.cfr") $ unlines+ [ "EU ?"+ , "age -> integer"+ ]+ result <- runClaferIGT (defaultIGArgs $ dir </> "static.cfr") $ do+ solve+ sequence [next, nextConfiguration, nextConfiguration]+ case fromRight result of+ [Instance (ClaferInstance model) _, Instance (ClaferInstance model') _, NoInstance] ->+ (("EU" `isInfixOf` show model) /= ("EU" `isInfixOf` show model')) @? "The configurations differ in EU"+ _ -> assertFailure "Two configurations"++-- | The traces given by next are distinct, and limited by the maximum trace length.+case_DynamicModelTraces :: Assertion+case_DynamicModelTraces = do+ dir <- testDir "DynamicModelTraces"+ writeFile (dir </> "light.cfr") trafficLight+ result <- runClaferIGT (defaultIGArgs $ dir </> "light.cfr") $ do+ setMaxTraceLength 3+ solve+ replicateM 5 next+ let traces = [show $ solutionText s | Instance s _ <- fromRight result]+ -- the traces of at most 3 states: one of 2 states and two of 3 states+ length traces == 3 @? ("3 traces of at most 3 states: " ++ show (length traces))+ length traces == length (nubOrd traces) @? "The traces are distinct"+ -- the reference of a clafer that is not in a state has any value, which is not shown:+ -- traces that differ only in it are the same trace+ writeFile (dir </> "absent.cfr") $ unlines+ [ "enum R = a | b"+ , "req -> R ?"+ , "[ never req ]"+ ]+ absent <- runClaferIGT (defaultIGArgs $ dir </> "absent.cfr") $ do+ setMaxTraceLength 1+ solve+ replicateM 3 next+ let absentTraces = [show $ solutionText s | Instance s _ <- fromRight absent]+ length absentTraces == 1 @? ("1 trace of 1 state without req: " ++ show absentTraces)+ where+ nubOrd = foldr (\x seen -> if x `elem` seen then seen else x : seen) []+++case_strMapCheck :: Assertion+case_strMapCheck = do+ --let claferModel = Right $ Instance (ClaferModel [(Clafer (Id "" 0) (Just (StringValue "")) [])]) ""+ claferModel' <- getModel "test/positive/i220.cfr"+ (valueCheck $ c_value $ head $ c_topLevel $ firstModel $ fromRight $ claferModel') @? "Mapping Int back to String Failed!"+ where+ valueCheck Nothing = False+ valueCheck (Just (AliasValue _)) = False+ valueCheck (Just (IntValue _)) = False+ valueCheck (Just (StringValue _)) = True++-- A model importing a file with --import in its //# OPTIONS directive; an error in the+-- imported file names it.+case_Imports :: Assertion+case_Imports = do+ dir <- testDir "Imports"+ writeFile (dir </> "lib.cfr") "abstract Lib\n x : integer\n [ x = 3 ]\n"+ writeFile (dir </> "model.cfr") "//# OPTIONS --import=lib.cfr\nA : Lib\n"+ instance' <- getModel $ dir </> "model.cfr"+ ("x -> 3" `isInfixOf` show (firstModel $ fromRight instance')) @? "The instance has the imported clafer's value"+ writeFile (dir </> "lib.cfr") "abstract Lib\n x : integer\n [ x = y ]\n"+ result <- getModel $ dir </> "model.cfr"+ case result of+ Left errs -> ("lib.cfr:3:11" `isInfixOf` show errs) @? ("The error names the imported file: " ++ show errs)+ Right _ -> assertFailure "The error in the imported file is not reported"++-- The constraints of an unsatisfiable core name the files that they are in.+case_ImportsUnsatCore :: Assertion+case_ImportsUnsatCore = do+ dir <- testDir "ImportsUnsatCore"+ writeFile (dir </> "lib2.cfr") "B\n y : integer\n [ y > 2 ]\n"+ writeFile (dir </> "unsat.cfr") "//# OPTIONS --import=lib2.cfr\n[ B.y < 2 ]\n"+ result <- getModel $ dir </> "unsat.cfr"+ case result of+ Right UnsatCore{unsatConstraints = core} -> do+ let shown = map show [ info | UserConstraint{constraintInfo = info} <- core ]+ any ("y > 2 (" `isPrefixOf`) shown && any ("lib2.cfr:3:7)" `isSuffixOf`) shown @? ("The core names lib2.cfr: " ++ show shown)+ any ("B.y < 2 (" `isPrefixOf`) shown && any ("unsat.cfr:2:3)" `isSuffixOf`) shown @? ("The core names unsat.cfr: " ++ show shown)+ _ -> assertFailure "The model has no unsatisfiable core"++-- The unsat core has the constraints of abstract clafers and of their children, each at its+-- position in the model (#46).+case_AbstractClaferUnsatCore :: Assertion+case_AbstractClaferUnsatCore = do+ dir <- testDir "AbstractClaferUnsatCore"+ writeFile (dir </> "engine.cfr") $ unlines+ [ "abstract Engine"+ , " power -> integer"+ , "gas : Engine"+ , " [ power = 2 ]"+ , "electric : Engine"+ , " [ power = 5 ]"+ , "abstract Car"+ , " abstract engine -> Engine"+ , " [ power >= 4 ]"+ , "golf : Car"+ , " motor : engine -> gas"+ ]+ writeFile (dir </> "car.cfr") $ unlines+ [ "abstract Car"+ , " x -> integer"+ , " [ this > 5 ]"+ , " [ x < 3 ]"+ , "golf : Car"+ ]+ engine <- runClaferIGT (defaultIGArgs $ dir </> "engine.cfr") $ do+ solve+ fastest <- next+ setUnsatCoreMinimization 0+ solve+ best <- next+ return (fastest, best)+ case fromRight engine of+ (UnsatCore{unsatConstraints = fastest}, UnsatCore{unsatConstraints = best}) -> do+ let core = shownCore fastest+ any ("power >= 4 (" `isPrefixOf`) core && any ("engine.cfr:9:11)" `isSuffixOf`) core @? ("The core has the constraint of the abstract engine: " ++ show core)+ any ("power = 2 (" `isPrefixOf`) core @? ("The core has the power of gas: " ++ show core)+ let minimal = shownCore best+ length minimal == 2 && not (any ("power = 5" `isPrefixOf`) minimal) @? ("The minimal core leaves out electric: " ++ show minimal)+ _ -> assertFailure "The model has no unsatisfiable core"+ car <- getModel $ dir </> "car.cfr"+ case fromRight car of+ UnsatCore{unsatConstraints = core'} -> do+ let core = shownCore core'+ any ("x < 3 (" `isPrefixOf`) core && any ("this > 5 (" `isPrefixOf`) core @? ("The core has both constraints of the abstract car: " ++ show core)+ _ -> assertFailure "The model has no unsatisfiable core"+ where+ shownCore core = map show [ info | UserConstraint{constraintInfo = info} <- core ]++-- The command c shows the scope of every clafer, also of the first one: the line of each+-- clafer's declaration names the clafer.+case_LineNumMapFirstClafer :: Assertion+case_LineNumMapFirstClafer = do+ dir <- testDir "LineNumMapFirstClafer"+ writeFile (dir </> "lines.cfr") "B\n y : integer\n [ y > 2 ]\nC\n"+ result <- runClaferIGT (defaultIGArgs $ dir </> "lines.cfr") getlineNumMap+ case result of+ Right lineNumMap -> Map.toList lineNumMap @?= [(1, "B"), (2, "y"), (4, "C")]+ Left errs -> assertFailure $ show errs
test/test-suite.hs view
@@ -20,17 +20,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -}-import Language.Clafer.IG.ClaferIG-import Language.Clafer.IG.ClaferModel import Language.Clafer.IG.CommandLine-import Control.Monad-import Control.Monad.IO.Class-import Data.Maybe-import Data.IORef-import System.Directory-import System.FilePath-import System.Console.CmdArgs-import Prelude hiding (all) import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH@@ -41,68 +31,6 @@ main :: IO () main = defaultMain $ testGroup "Tests" [ tg_testsuite ] -claferIGArgsDef :: IGArgs-claferIGArgsDef = IGArgs {- all = def,- saveDir = def,- claferModelFile = def,- alloySolution = def,- bitwidth = 4,- maxInt = 7,- useUids = False,- addTypes = False,- json = False,- flatten_inheritance_comp = False,- no_layout_comp = False,- check_duplicates_comp = False,- skip_resolver_comp = False,- scope_strategy_comp = def-} &= summary claferIGVersion---defaultIGArgs :: FilePath -> IGArgs---defaultIGArgs fPath = IGArgs Nothing Nothing fPath False 4 False False False-defaultIGArgs fPath = claferIGArgsDef{claferModelFile = fPath}----getModel :: MonadIO m => FilePath -> ClaferIGT m (Either Language.ClaferT.ClaferErrs Instance)-getModel fPath = runClaferIGT (defaultIGArgs fPath) $ do- setGlobalScope (fromMaybe 1 $ all $ defaultIGArgs fPath)- solve- counterRef <- liftIO $ newIORef 1- let saveDirectory = fromMaybe return $ underDirectory `liftM` saveDir (defaultIGArgs fPath)- let nextFile = savePath fPath counterRef >>= saveDirectory- file <- liftIO nextFile- liftIO $ createDirectoryIfMissing True $ takeDirectory file- next- where- savePath :: FilePath -> IORef Int -> IO FilePath- savePath fPath' counterRef =- do- counter <- readIORef counterRef- writeIORef counterRef (counter + 1)- return $ fPath' ++ "." ++ (show counter) ++ ".data"- underDirectory :: FilePath -> FilePath -> IO FilePath- underDirectory dir file =- do- createDirectoryIfMissing True dir- return $ joinPath [dir, file]---fromRight (Right x) = x-fromRight _ = error "fromRight received Left _. Should never happen."---case_strMapCheck :: Assertion-case_strMapCheck = do- --let claferModel = Right $ Instance (ClaferModel [(Clafer (Id "" 0) (Just (StringValue "")) [])]) ""- claferModel' <- getModel "test/positive/i220.cfr"- (valueCheck $ c_value $ head $ c_topLevel $ modelInstance $ fromRight $ claferModel') @? "Mapping Int back to String Failed!"- where- valueCheck Nothing = False- valueCheck (Just (AliasValue _)) = False- valueCheck (Just (IntValue _)) = False- valueCheck (Just (StringValue _)) = True- case_pickLargerScope :: Assertion case_pickLargerScope = do let@@ -111,5 +39,3 @@ mergedScopes = map (pickLargerScope oldScopes) newScopes mergedScopes @?= [ ("c0_1", 2), ("c0_b", 2), ("c1_b", 2)]--