repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
cryptoguard
cryptoguard-master/src/test/java/frontEnd/Interface/parameterChecks/ContainerTest.java
/* Licensed under GPL-3.0 */ package frontEnd.Interface.parameterChecks; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author franceme Created on 2020-11-17. * @since {VersionHere} * <p>ContainerTest * <p>{Description Here} */ public class ContainerTest { //region Attributes //endregion //region Test Environment Setup @Before public void setup() {} @After public void tearDown() {} //endregion //region Tests @Test public void baseTest() { String baseContainer = new Container().toString(); String baseResult = "\"Container\": {\"javaHome\":\"None\",\"androidHome\":\"None\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } @Test public void javaHomeTest() { String fakePath = "/fake/path/here"; String baseContainer = new Container().withJavaHome(fakePath).toString(); String baseResult = "\"Container\": {\"javaHome\":\"" + fakePath + "\",\"androidHome\":\"None\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } @Test public void javaHome_AndroidHome_Test() { String fakePath = "/fake/path/here"; String fakePathTwo = "/fake/path/here/again"; String baseContainer = new Container().withJavaHome(fakePath).withAndroidHome(fakePathTwo).toString(); String baseResult = "\"Container\": {\"javaHome\":\"" + fakePath + "\",\"androidHome\":\"" + fakePathTwo + "\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } @Test public void sourceFil_Test() { String fakePath = "/fake/path/here"; String baseContainer = new Container().addSourceValue(fakePath).toString(); String baseResult = "\"Container\": {\"javaHome\":\"None\",\"androidHome\":\"None\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[\"" + fakePath + "\"],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } @Test public void sourceFiles_Test() { String fakePath = "/fake/path/here"; String fakePathTwo = "/fake/path/here/again"; String baseContainer = new Container().addSourceValue(fakePath).addSourceValue(fakePathTwo).toString(); String baseResult = "\"Container\": {\"javaHome\":\"None\",\"androidHome\":\"None\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[\"" + fakePath + "\",\"" + fakePathTwo + "\"],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } @Test public void sourceFiles_AddAll_Test() { ArrayList<String> fakeArray = new ArrayList<>(); String fakePath = "/fake/path/here"; String fakePathTwo = "/fake/path/here/again"; fakeArray.add(fakePath); fakeArray.add(fakePathTwo); String baseContainer = new Container().addSourceValues(fakeArray).toString(); String baseResult = "\"Container\": {\"javaHome\":\"None\",\"androidHome\":\"None\",\"debuggingLevel\":-1,\"listing\":{ \"type\": \"Default\", \"flag\": \"D\"},\"engineType\":\"CLASSFILES\",\"sourceValues\":[\"" + fakePath + "\",\"" + fakePathTwo + "\"],\"dependencyValues\":[],\"overwriteOutFile\":false,\"outFile\":\"None\",\"mainFile\":\"None\",\"prettyPrint\":true,\"showTimes\":false,\"streaming\":true,\"displayHeuristics\":false,\"scanningDepth\":\"None\",\"packageName\":\"None\"}"; assertEquals(baseResult, baseContainer); } //endregion }
5,229
42.583333
434
java
cryptoguard
cryptoguard-master/src/test/java/frontEnd/MessagingSystem/routing/inputStructures/LegacyTest.java
/* Licensed under GPL-3.0 */ package frontEnd.MessagingSystem.routing.inputStructures; import org.junit.After; import org.junit.Before; /** * LegacyTest class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ public class LegacyTest { //region Attributes //endregion //region Test Environment Management /** * setUp. * * @throws java.lang.Exception if any. */ @Before public void setUp() throws Exception {} /** * tearDown. * * @throws java.lang.Exception if any. */ @After public void tearDown() throws Exception {} //endregion }
601
14.842105
57
java
cryptoguard
cryptoguard-master/src/test/java/frontEnd/MessagingSystem/routing/inputStructures/ScarfXMLTest.java
/* Licensed under GPL-3.0 */ package frontEnd.MessagingSystem.routing.inputStructures; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static util.Utils.makeArg; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import frontEnd.Interface.formatArgument.ScarfXML; import frontEnd.MessagingSystem.routing.EnvironmentInformation; import frontEnd.MessagingSystem.routing.Listing; import frontEnd.MessagingSystem.routing.structure.Scarf.Method; import frontEnd.argsIdentifier; import java.util.Arrays; import java.util.Collections; import java.util.Properties; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import rule.engine.EngineType; /** * ScarfXMLTest class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ @RunWith(MockitoJUnitRunner.class) public class ScarfXMLTest { private final EngineType type = EngineType.APK; private final String dependencies = null; //region Attributes private EnvironmentInformation testInfo; private ScarfXML inputTest; private String assessment_start_ts; private String build_fw; private String build_fw_version; private String package_name; private String package_version; private String assess_fw; private String assess_fw_version; private String build_root_dir; private String package_root_dir; private String parser_fw; private String parser_fw_version; private String uuid; private Properties sampleProp = new Properties(); //endregion //region Test Environment Management /** * setUp. * * @throws java.lang.Exception if any. */ @Before public void setUp() throws Exception { inputTest = spy(ScarfXML.class); assess_fw = "java-assess"; assess_fw_version = "1.0.0c"; assessment_start_ts = "1516116551.639144"; build_fw = "c-assess"; build_fw_version = "1.1.12"; build_root_dir = "/home"; package_name = "Rigorityj"; package_root_dir = "CryptoGuard"; package_version = "8675309"; parser_fw = "example_tool"; parser_fw_version = "x.y.z"; uuid = "fa109792-9234-4jk2-9f68-alp9woofbeef"; sampleProp.setProperty("assess_fw", assess_fw); sampleProp.setProperty("assess_fw_version", assess_fw_version); sampleProp.setProperty("assessment_start_ts", assessment_start_ts); sampleProp.setProperty("build_fw", build_fw); sampleProp.setProperty("build_fw_version", build_fw_version); sampleProp.setProperty("build_root_dir", build_root_dir); sampleProp.setProperty("package_name", package_name); sampleProp.setProperty("package_root_dir", package_root_dir); sampleProp.setProperty("parser_fw", parser_fw); sampleProp.setProperty("parser_fw_version", parser_fw_version); sampleProp.setProperty("package_version", package_version); parser_fw = "example_tool"; parser_fw_version = "x.y.z"; sampleProp.setProperty("uuid", uuid); } /** * tearDown. * * @throws java.lang.Exception if any. */ @After public void tearDown() throws Exception { testInfo = null; inputTest = null; assess_fw = null; assess_fw_version = null; assessment_start_ts = null; build_fw = null; build_fw_version = null; build_root_dir = null; package_root_dir = null; package_name = null; package_root_dir = null; package_version = null; parser_fw = null; parser_fw_version = null; uuid = null; sampleProp = null; } //endregion /** simpleTest_1. */ @Test public void simpleTest_1() { try { Method method = new Method(23, true, "hai"); XmlMapper xmlMapper = new XmlMapper(); String xml = xmlMapper.writeValueAsString(method); assertNotNull(xml); System.out.println(xml); } catch (JsonProcessingException e) { assertNull(e); e.printStackTrace(); } } /** testAllArguments_inputValidation. */ @Test public void testAllArguments_inputValidation() { StringBuilder args = new StringBuilder(); //region Setting the arguments string args.append(makeArg(argsIdentifier.SCONFIG.getId(), assess_fw)); //endregion try { testInfo = new EnvironmentInformation( Collections.singletonList("test"), EngineType.JAR, Listing.ScarfXML, null, Collections.singletonList("test"), ""); doReturn(sampleProp).when(inputTest).loadProperties(Mockito.anyString()); assertTrue( inputTest.inputValidation( testInfo, Arrays.stream(args.toString().split(" ")).collect(Collectors.toList()))); //region Checking arguments assertEquals(assess_fw, testInfo.getAssessmentFramework()); assertEquals(assess_fw_version, testInfo.getAssessmentFrameworkVersion()); assertEquals(assessment_start_ts, testInfo.getAssessmentStartTime()); assertEquals(build_fw, testInfo.getBuildFramework()); assertEquals(build_fw_version, testInfo.getBuildFrameworkVersion()); assertEquals(build_root_dir, testInfo.getBuildRootDir()); assertEquals(package_root_dir, testInfo.getPackageRootDir()); assertEquals(package_name, testInfo.getPackageName()); assertEquals(package_version, testInfo.getPackageVersion()); assertEquals(uuid, testInfo.getUUID()); //endregion } catch (Exception e) { assertNull(e); e.printStackTrace(); } } }
5,830
30.349462
97
java
cryptoguard
cryptoguard-master/src/test/java/frontEnd/MessagingSystem/routing/structure/Scarf/AnalyzerReportTest.java
/* Licensed under GPL-3.0 */ package frontEnd.MessagingSystem.routing.structure.Scarf; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * AnalyzerReportTest class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ public class AnalyzerReportTest { private Method method; /** * setUp. * * @throws java.lang.Exception if any. */ @Before public void setUp() throws Exception {} /** * tearDown. * * @throws java.lang.Exception if any. */ @After public void tearDown() throws Exception { method = null; } /** simpleTest_1. */ @Test public void simpleTest_1() { try { method = new Method(23, true, "hai"); XmlMapper xmlMapper = new XmlMapper(); String xml = xmlMapper.writeValueAsString(method); assertNotNull(xml); System.out.println(xml); } catch (JsonProcessingException e) { assertNull(e); e.printStackTrace(); } } }
1,178
19.327586
58
java
cryptoguard
cryptoguard-master/src/test/java/rule/engine/RuleListTest.java
/* Licensed under GPL-3.0 */ package rule.engine; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertTrue; import CWE_Reader.CWE; import CWE_Reader.CWEList; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * RuleListTest class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ public class RuleListTest { //region Attributes private final CWEList cwes = new CWEList(); //endregion //region Test Environment Setup /** * setUp. * * @throws java.lang.Exception if any. */ @Before public void setUp() throws Exception {} /** * tearDown. * * @throws java.lang.Exception if any. */ @After public void tearDown() throws Exception {} //endregion //region Tests /** testGetRulesByNumber. */ @Test public void testGetRulesByNumber() { for (RuleList rule : RuleList.values()) assertEquals(rule, RuleList.getRuleByRuleNumber(rule.getRuleId())); } /** testCWEListing. */ @Test public void testCWEListing() { for (RuleList rule : RuleList.values()) if (rule.getRuleId() != -1) for (CWE cwe : rule.retrieveCWEInfo(cwes)) assertTrue(cwe.getId() != -1); } //endregion }
1,243
18.746032
81
java
cryptoguard
cryptoguard-master/src/test/java/test/TestUtilities.java
/* Licensed under GPL-3.0 */ package test; import static junit.framework.TestCase.assertTrue; import frontEnd.Interface.EntryPoint; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; import util.Utils; /** * TestUtilities class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ public class TestUtilities { //region String Statics public static final Boolean isLinux = !System.getProperty("os.name").contains("Windows"); public static final String basePath = System.getProperty("user.dir"); public static final String scarfArgs = Utils.osPathJoin(basePath, "src", "main", "resources", "Scarf", "sample.properties"); public static final String testRec = Utils.osPathJoin(basePath, "samples"); public static final String testPath = Utils.osPathJoin(basePath, "build", "tmp"); public static final String testRec_tester_test = Utils.osPathJoin(testRec, "temp", "tester"); public static final String testRec_tester_test_Class = Utils.osPathJoin(testRec_tester_test, "test.class"); public static final String testRec_tester_test_Java = Utils.osPathJoin(testRec_tester_test, "test.java"); public static final String testRec_tester_test_Java_xml = Utils.osPathJoin(testPath, "test_java.xml"); public static final String srcOneGrv = Utils.osPathJoin(testRec, "testable-jar"); public static final String pracitceJavaPackage = Utils.osPathJoin(srcOneGrv, "src", "main", "java", "tester", "Crypto_VeryTemp.java"); public static final String verySimple_Gradle = Utils.osPathJoin(testRec, "VerySimple_Gradle"); public static final String verySimple_Gradle_File = Utils.osPathJoin(verySimple_Gradle, "src", "main", "java", "very.java"); public static final String crypto_Example = Utils.osPathJoin(testRec, "Crypto_Example"); public static final String crypto_Example_File = Utils.osPathJoin(crypto_Example, "src", "main", "java", "Crypto.java"); public static final String passwordUtils_Example = Utils.osPathJoin(testRec, "PasswordUtils_Example"); public static final String passwordUtils_Example_File = Utils.osPathJoin(passwordUtils_Example, "src", "main", "java", "PasswordUtils.java"); public static final String symCrypto_Example = Utils.osPathJoin(testRec, "SymCrypto_Example"); public static final String symCrypto_Example_File = Utils.osPathJoin(symCrypto_Example, "src", "main", "java", "SymCrypto.java"); public static final String symCrypto_Package_Example = Utils.osPathJoin(testRec, "SymCrypto_Package_Example"); public static final String symCrypto_Example_Package_File = Utils.osPathJoin( symCrypto_Package_Example, "src", "main", "java", "tester", "SymCrypto.java"); public static final String symCrypto_Multiple_Example = Utils.osPathJoin(testRec, "SymCrypto_Multi_Example"); public static final String symCrypto_Multiple_Example_File_1 = Utils.osPathJoin(symCrypto_Multiple_Example, "src", "main", "java", "SymCrypto.java"); public static final String symCrypto_Multiple_Example_File_2 = Utils.osPathJoin(symCrypto_Multiple_Example, "src", "main", "java", "PassEncryptor.java"); public static final String srcOneGrv_base = "tester"; public static final String srcOneGrvInputFile = Utils.osPathJoin(srcOneGrv, "input.in"); public static final String javaSource = Utils.osPathJoin(srcOneGrv, "src", "main", "java", "tester"); public static final String classSource = Utils.osPathJoin(srcOneGrv, "build", "classes", "java", "main", "tester"); public static final String[] classFiles = { Utils.osPathJoin(classSource, "PBEUsage.class"), Utils.osPathJoin(classSource, "UrlFrameWorks.class"), Utils.osPathJoin(classSource, "NewTestCase1.class"), Utils.osPathJoin(classSource, "NewTestCase2.class") }; public static final String newTestCaseTwo_Class = Utils.osPathJoin(classSource, "NewTestCase2.class"); public static final String newTestCaseTwo_xml = Utils.osPathJoin(testPath, "NewTestCase2-class.xml"); public static final String newTestCaseTwo_xml_0 = Utils.osPathJoin(testPath, "NewTestCase2-class_0.xml"); public static final String testablejar_Crypto_plugin_class_json = Utils.osPathJoin(testPath, "java-plugin-file_One.json"); public static final String testablejar_Crypto_plugin_class_json_0 = Utils.osPathJoin(testPath, "java-plugin-file_One_0.json"); public static final String testablejar_PBEUsage_class_xml = Utils.osPathJoin(testPath, "PBEUsage-class-file_One.xml"); public static final String testablejar_Crypto_class = Utils.osPathJoin(classSource, "Crypto.class"); public static final String testablejar_Crypto_class_xml = Utils.osPathJoin(testPath, "java-file_One.xml"); public static final String testablejar_Crypto_class_xml_0 = Utils.osPathJoin(testPath, "java-file_One_0.xml"); public static final String[] javaFiles = { Utils.osPathJoin(javaSource, "PBEUsage.java"), Utils.osPathJoin(javaSource, "UrlFrameWorks.java") }; public static final String jarOne = Utils.osPathJoin(testRec, "testable-jar", "build", "libs", "testable-jar.jar"); public static final String srcOneGrvDep = Utils.osPathJoin(testRec, "testable-jar", "build", "dependencies"); public static final String javaFileOne = Utils.osPathJoin(testPath, "java-file_One.xml"); public static final String javaFileTwo = Utils.osPathJoin(testPath, "java-file_Two.txt"); public static final String javaFileThree = Utils.osPathJoin(testPath, "java-file_Three.txt"); public static final String javaFileThreeXML = Utils.osPathJoin(testPath, "java-file_Three.xml"); public static final String pathToSchema = Utils.osPathJoin(basePath, "src", "main", "resources", "Scarf", "scarf_v1.2.xsd"); public static final String pathToAPK = Utils.osPathJoin(testRec, "app-debug.apk"); public static final String tempFileOutTxt = Utils.osPathJoin(testPath, "testable-jar.txt"); public static final String tempFileOutXML = Utils.osPathJoin(testPath, "testable-jar.xml"); public static final String tempFileOutJSON = Utils.osPathJoin(testPath, "testable-jar.json"); public static final String tempTestJJava_Txt = Utils.osPathJoin(testPath, "temp_java-jar.txt"); public static final String tempStreamXML = Utils.osPathJoin(testPath, "testable-jar_Stream.xml"); public static final String tempFileOutTxt_two = Utils.osPathJoin(testPath, "testable-jar_classFiles.txt"); public static final String tempFileOutTxt_two_0 = Utils.osPathJoin(testPath, "testable-jar_classFiles_0.txt"); public static final String tempFileOutTxt_default = Utils.osPathJoin(testPath, "testable-jar_classFiles.json"); public static final String tempFileOutTxt_default_0 = Utils.osPathJoin(testPath, "testable-jar_classFiles_0.json"); public static final String tempFileOutXML_two = Utils.osPathJoin(testPath, "testable-jar_classFiles.xml"); public static final String tempFileOutTxt_Class = Utils.osPathJoin(testPath, "java-class-file.txt"); public static final String tempFileOutTxt_Class_fullproj = Utils.osPathJoin(testPath, "java-class-proj-file.xml"); public static final String tempFileOutTxt_Class_fullproj_0 = Utils.osPathJoin(testPath, "java-class-proj-file_0.xml"); public static final String tempFileOutTxt_Class_tester_test = Utils.osPathJoin(testPath, "java-class-file_sample_tester-test.txt"); public static final String tempFileOutXML_Class_0 = Utils.osPathJoin(testPath, "java-class-file_0.xml"); public static final String tempFileOutXML_Class_1 = Utils.osPathJoin(testPath, "java-class-file_1.xml"); public static final String tempFileOutXML_Class_Stream_0 = Utils.osPathJoin(testPath, "java-class-file-stream_0.xml"); public static final String tempFileOutApk = Utils.osPathJoin(testPath, "app-debug.txt"); public static final String tempFileOutApk_CSV = Utils.osPathJoin(testPath, "app-debug.csv"); public static final String tempFileOutApk_Steam = Utils.osPathJoin(testPath, "app-debug_Stream.txt"); public static final String tempFileOutApk_CSVStream = Utils.osPathJoin(testPath, "app-debug_Stream.csv"); public static final String tempFileOutApk_YAMLStream = Utils.osPathJoin(testPath, "app-debug_Stream.yaml"); public static final String tempFileOutApk_Scarf = Utils.osPathJoin(testPath, "app-debug.xml"); public static final String tempFileOutApk_Scarf_XArgs = Utils.osPathJoin(testPath, "app-debug_XArgs.xml"); public static final String tempFileOutApk_Scarf_Steam = Utils.osPathJoin(testPath, "app-debug_Stream.xml"); public static final String tempFileOutApk_Default = Utils.osPathJoin(testPath, "app-debug.json"); public static final String tempFileOutApk_Default_Steam = Utils.osPathJoin(testPath, "app-debug_Stream.json"); public static final String tempFileOutJson_Project = Utils.osPathJoin(testPath, "very-simple_Project.json"); public static final String crypto_Example_Json_Project = Utils.osPathJoin(testPath, "Crypto_Example_Project.json"); public static final String passwordUtils_Example_Json_Project = Utils.osPathJoin(testPath, "PasswordUtils_Example_Project.json"); public static final String symCrypto_Example_Json_Project = Utils.osPathJoin(testPath, "SymCrypto_Example_Project.json"); public static final String tempFileOutJson_File = Utils.osPathJoin(testPath, "very-simple_File.json"); public static final String crypto_Example_Json_File = Utils.osPathJoin(testPath, "Crypto_Example_File.json"); public static final String passwordUtils_Example_Json_File = Utils.osPathJoin(testPath, "PasswordUtils_Example_File.json"); public static final String symCrypto_Example_Json_File = Utils.osPathJoin(testPath, "SymCrypto_Example_File.json"); public static final String symCrypto_Example_Package_Json_File = Utils.osPathJoin(testPath, "SymCrypto_Package_Example_File.json"); public static final String symCrypto_Multiple_Files = Utils.osPathJoin(testPath, "SymCrypto_Example_Files.json"); public static final String tempJarFile_txt = Utils.osPathJoin(testPath, "tempJarFile_txt.txt"); public static final String tempJarFile_Scarf_0 = Utils.osPathJoin(testPath, "tempJarFile_Scarf_0.xml"); public static final String tempJarFile_Scarf_1 = Utils.osPathJoin(testPath, "tempJarFile_Scarf_1.xml"); public static final String tempJarFile_Scarf_2 = Utils.osPathJoin(testPath, "tempJarFile_Scarf_2.xml"); public static final String tempJarFile_Scarf_Steam_1 = Utils.osPathJoin(testPath, "tempJarFile_Scarf_Steam_1.xml"); public static final String tempJarFile_Default_0 = Utils.osPathJoin(testPath, "tempJarFile_Default_0.json"); public static final String tempJarFile_Default_Stream_0 = Utils.osPathJoin(testPath, "tempJarFile_Default_Stream_0.json"); public static final ArrayList<String> sampleAuxClassPathOneList = new ArrayList<>( Arrays.asList(testRec, jarOne, javaFiles[0], javaFiles[1], classFiles[0], classFiles[1])); public static final String sampleAuxClassPathOne = String.join(":", sampleAuxClassPathOneList); public static final ArrayList<String> sampleAuxClassPathTwoList = new ArrayList<>( Arrays.asList( testRec, jarOne, javaFiles[0], javaFiles[1], classFiles[0], classFiles[1], scarfArgs)); public static final String sampleAuxClassPathTwo = String.join(":", sampleAuxClassPathTwoList); public static final String verySimple_Path_NonVuln = Utils.osPathJoin(testRec, "VerySimple_NonVuln"); public static final String verySimple_Jar_NonVuln = Utils.osPathJoin(verySimple_Path_NonVuln, "very.jar"); public static final String verySimple_Jar_xml_NonVuln = Utils.osPathJoin(testPath, "verySimple_jar_NonVuln.xml"); public static final String verySimple_Jar_json_NonVuln = Utils.osPathJoin(testPath, "verySimple_jar_NonVuln.json"); public static final String verySimple_Jar_csv_NonVuln = Utils.osPathJoin(testPath, "verySimple_jar_NonVuln.csv"); public static final String verySimple_Java_NonVuln = Utils.osPathJoin(verySimple_Path_NonVuln, "very.java"); public static final String verySimple_Java_xml_NonVuln = Utils.osPathJoin(testPath, "verySimple_java_NonVuln.xml"); public static final String verySimple_Klass_NonVuln = Utils.osPathJoin(verySimple_Path_NonVuln, "very.class"); public static final String verySimple_Path = Utils.osPathJoin(testRec, "VerySimple"); public static final String verySimple_Jar = Utils.osPathJoin(verySimple_Path, "very.jar"); public static final String verySimple_Jar_xml = Utils.osPathJoin(testPath, "verySimple_jar.xml"); public static final String verySimple_Java = Utils.osPathJoin(verySimple_Path, "very.java"); public static final String verySimple_Java_xml = Utils.osPathJoin(testPath, "verySimple_java.xml"); public static final String verySimple_Klass = Utils.osPathJoin(verySimple_Path, "very.class"); public static final String verySimple_Klass_xml = Utils.osPathJoin(testPath, "verySimple_klass.xml"); public static final String verySimple_Klass_xml_0 = Utils.osPathJoin(testPath, "verySimple_klass_0.xml"); public static final String verySimple_Klass_xml_1 = Utils.osPathJoin(testPath, "verySimple_klass_1.xml"); public static final String verySimple_Klass_csv_1 = Utils.osPathJoin(testPath, "verySimple_klass_1.csv"); public static final String verySimple_Klass_xml_2 = Utils.osPathJoin(testPath, "verySimple_klass_2.xml"); public static final String verySimple_Klass_yaml_1 = Utils.osPathJoin(testPath, "verySimple_klass_2.yaml"); public static final ArrayList<String> srcOneGrvInputArr = new ArrayList<>( Arrays.asList( Utils.osPathJoin(javaSource, "UrlFrameWorks.java"), Utils.osPathJoin(javaSource, "PasswordUtils.java"), Utils.osPathJoin(javaSource, "Crypto.java"), Utils.osPathJoin(javaSource, "PBEUsage.java"), Utils.osPathJoin(javaSource, "NewTestCase2.java"), Utils.osPathJoin(javaSource, "VeryBusyClass.java"), Utils.osPathJoin(javaSource, "SymCrypto.java"), Utils.osPathJoin(javaSource, "NewTestCase1.java"), Utils.osPathJoin(javaSource, "LiveVarsClass.java"), Utils.osPathJoin(javaSource, "PassEncryptor.java"))); public static final ArrayList<String> srcOneGrvInputArr_Class = new ArrayList<>( Arrays.asList( Utils.osPathJoin(classSource, "UrlFrameWorks.class"), Utils.osPathJoin(classSource, "PasswordUtils.class"), Utils.osPathJoin(classSource, "Crypto.class"), Utils.osPathJoin(classSource, "Crypto$1.class"), Utils.osPathJoin(classSource, "Crypto$2.class"), Utils.osPathJoin(classSource, "Crypto$3.class"), Utils.osPathJoin(classSource, "PBEUsage.class"), Utils.osPathJoin(classSource, "NewTestCase2.class"), Utils.osPathJoin(classSource, "VeryBusyClass.class"), Utils.osPathJoin(classSource, "SymCrypto.class"), Utils.osPathJoin(classSource, "NewTestCase1.class"), Utils.osPathJoin(classSource, "LiveVarsClass.class"), Utils.osPathJoin(classSource, "PassEncryptor.class"))); //endregion public static String[] cleaningArgs(String arg) { ArrayList<String> cleanArgs = new ArrayList<>(Arrays.asList(arg.split(" "))); cleanArgs.removeIf(StringUtils::isEmpty); return cleanArgs.toArray(new String[cleanArgs.size()]); } public static String resetFileOut(String path) { new File(path).delete(); return path; } public static String captureNewFileOutViaStdOut(String[] args, Boolean exceptionHandler) { //region Redirecting the std out to capture the file out //The new std out ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); //Old out PrintStream old = System.out; //Redirecting the std out to the capture System.setOut(ps); //region Critical Section EntryPoint.main(args); //endregion //Resetting the std out System.out.flush(); System.setOut(old); //endregion //The output string String outputString = StringUtils.trimToNull(baos.toString()); if (!exceptionHandler) assertTrue(StringUtils.isNotBlank(outputString)); String[] lines = baos.toString().split(Utils.lineSep); outputString = StringUtils.trimToNull(lines[lines.length - 1]); if (!exceptionHandler) assertTrue(StringUtils.isNotBlank(outputString)); return outputString; } public static String captureNewFileOutViaStdOut(String[] args) throws Exception { return captureNewFileOutViaStdOut(args, false); } public static String[] arr(ArrayList<String> in) { return in.toArray(new String[in.size()]); } public static ArrayList<String> arr(String[] in) { return new ArrayList<>(Arrays.asList(in)); } public static String getFileNameFromString(String filePath) { if (StringUtils.isBlank(filePath)) return ""; filePath = StringUtils.trimToNull(filePath); String[] splits = filePath.split(Utils.fileSep); String fileName = splits[splits.length - 1]; return StringUtils.trimToNull(fileName.substring(0, fileName.indexOf("."))); } public static String retrieveFilesFromDir(String dir, String name) { ProcessBuilder cmd = new ProcessBuilder(); cmd.command(("find " + dir + " -name " + name).split(" ")); StringBuilder output = new StringBuilder(); try { Process exe = cmd.start(); String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(exe.getInputStream()))) { while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } } catch (Exception e) { } } catch (Exception e) { } return output.toString(); } public static InputStream setIn(String string) { InputStream input = System.in; System.setIn(new ByteArrayInputStream(string.getBytes())); return input; } }
18,482
47.76781
100
java
cryptoguard
cryptoguard-master/src/test/java/util/UtilsTest.java
/* Licensed under GPL-3.0 */ package util; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static test.TestUtilities.*; import static util.Utils.join; import static util.Utils.trimFilePath; import frontEnd.Interface.outputRouting.ExceptionHandler; import frontEnd.Interface.outputRouting.ExceptionId; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import test.TestUtilities; /** * UtilsTest class. * * @author franceme * @version $Id: $Id * @since V03.03.10 */ public class UtilsTest { //region Attributes private String fullJavaClassFile; private String fullJavaFile; private String fileSep = System.getProperty("file.separator"); //endregion //region Test Environment /** * setUp. * * @throws java.lang.Exception if any. */ @Before public void setUp() throws Exception { fullJavaFile = String.join(fileSep, "src", "main", "java", "com", "full", "fun", "test", "main.java"); fullJavaClassFile = String.join(fileSep, "target", "main", "java", "com", "full", "fun", "test", "main.class"); } /** * tearDown. * * @throws java.lang.Exception if any. */ @After public void tearDown() throws Exception { fullJavaFile = null; fullJavaClassFile = null; } //endregion //region Tests /** trimFilePathTestOne. */ @Test public void trimFilePathTestOne() { String fileNameExt = trimFilePath(fullJavaFile); assertNotNull(fileNameExt); assertEquals("main.java", fileNameExt); } /** trimFilePathTestTwo. */ @Test public void trimFilePathTestTwo() { String fileNameExt = trimFilePath(fullJavaClassFile); assertNotNull(fileNameExt); assertEquals("main.class", fileNameExt); } @Test public void testVerifyClassPathsOne() { try { ArrayList<String> returnedOutput = Utils.retrieveFilePathTypes( TestUtilities.sampleAuxClassPathOne, null, false, false, true); for (String output : returnedOutput) assertTrue(TestUtilities.sampleAuxClassPathOneList.contains(output)); } catch (Exception e) { System.out.println(e.getMessage()); assertNull(e); } } @Test public void testVerifyClassPathsTwo() { try { ArrayList<String> returnedOutput = Utils.retrieveFilePathTypes( TestUtilities.sampleAuxClassPathTwo, null, false, false, true); TestUtilities.sampleAuxClassPathTwoList.forEach( str -> assertTrue(returnedOutput.contains(str))); assertEquals(TestUtilities.sampleAuxClassPathTwoList.size(), returnedOutput.size()); } catch (ExceptionHandler e) { assertEquals(e.getErrorCode(), ExceptionId.ARG_VALID); assertTrue(e.getLongDesciption().contains(TestUtilities.scarfArgs)); } } @Test public void test_retrieveFullyQualifiedPath_Single() { String testFile = classFiles[0]; String base = join(".", "tester", classFiles[0].replace(classSource + "/", "").replace(".class", "")); try { String fullyQualifiedName = Utils.retrieveFullyQualifiedName(testFile); assertEquals(base, fullyQualifiedName); } catch (Exception e) { System.out.println(e.getMessage()); assertNull(e); } } @Test public void test_retrievePackageFromJavaFiles() { String testFile = pracitceJavaPackage; String pkg = "tester/Crypto_VeryTemp.java"; try { String fullyQualifiedName = Utils.retrievePackageFromJavaFiles(testFile); assertEquals(pkg, fullyQualifiedName); } catch (Exception e) { System.out.println(e.getMessage()); assertNull(e); } } @Test public void test_retrieveFullyQualifiedName() { String testFile = pracitceJavaPackage; String pkg = "tester" + ".Crypto_VeryTemp"; try { String fullyQualifiedName = Utils.retrieveFullyQualifiedName(testFile); assertEquals(pkg, fullyQualifiedName); } catch (Exception e) { System.out.println(e.getMessage()); assertNull(e); } } //endregion }
4,202
25.770701
99
java
java-smt
java-smt-master/doc/Example-Gradle-Project-Kotlin/src/test/java/org/sosy_lab/java_smt_example/SudokuTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_example; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.sosy_lab.java_smt.example.Sudoku.SIZE; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.log.BasicLogManager; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.Sudoku.IntegerBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.BooleanBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.SudokuSolver; /** * This program parses a String-given Sudoku and solves it with an SMT solver. * * <p>This program is just an example and clearly SMT is not the best solution for solving Sudoku. * There might be other algorithms out there that are better suited for solving Sudoku. * * <p>The more numbers are available in a Sudoku, the easier it can be solved. A completely empty * Sudoku will cause the longest runtime in the solver, because it will guess a lot of values. * * <p>The Sudoku is read from a String and should be formatted as the following example: * * <pre> * 2..9.6..1 * ..6.4...9 * ...52.4.. * 3.2..7.5. * ...2..1.. * .9.3..7.. * .87.5.31. * 6.3.1.8.. * 4....9... * </pre> * * <p>The solution will then be printed on StdOut and checked by an assertion, just like the * following solution: * * <pre> * 248976531 * 536148279 * 179523468 * 312487956 * 764295183 * 895361742 * 987652314 * 623714895 * 451839627 * </pre> */ public class SudokuTest { private Configuration config; private LogManager logger; private ShutdownNotifier notifier; private SolverContext context; private static final String input = "2..9.6..1\n" + "..6.4...9\n" + "...52.4..\n" + "3.2..7.5.\n" + "...2..1..\n" + ".9.3..7..\n" + ".87.5.31.\n" + "6.3.1.8..\n" + "4....9..."; private static final String sudokuSolution = "248976531\n" + "536148279\n" + "179523468\n" + "312487956\n" + "764295183\n" + "895361742\n" + "987652314\n" + "623714895\n" + "451839627\n"; public SudokuTest() { } private void init() throws InvalidConfigurationException { config = Configuration.defaultConfiguration(); logger = BasicLogManager.create(config); notifier = ShutdownNotifier.createDummy(); } /* * We close our context after we are done with a solver to not waste memory. */ private final void closeSolver() { if (context != null) { context.close(); } } public void princessSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.PRINCESS); closeSolver(); } public void smtInterpolSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.SMTINTERPOL); closeSolver(); } public void cvc4SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.CVC4); closeSolver(); } public void z3SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.Z3); closeSolver(); } public void mathsatSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.MATHSAT5); closeSolver(); } public void boolectorSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); // Boolector does not support Integers checkSudokuWithBooleans(Solvers.BOOLECTOR); closeSolver(); } public void yicesSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { init(); checkSudoku(Solvers.YICES2); closeSolver(); } private void checkSudoku(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new IntegerBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } // Same as checkSudoku but with Booleans instead of Integers private void checkSudokuWithBooleans(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new BooleanBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } private String solutionToString(Integer[][] solution) { StringBuilder sb = new StringBuilder(); for (Integer[] s1 : solution) { sb.append(Joiner.on("").join(s1)).append('\n'); } return sb.toString(); } /** * a simple parser for a half-filled Sudoku. * * <p>Use digits 0-9 as values, other values will be set to 'unknown'. */ private Integer[][] readGridFromString(String puzzle) { Integer[][] grid = new Integer[SIZE][SIZE]; List<String> lines = Splitter.on('\n').splitToList(puzzle); for (int row = 0; row < lines.size(); row++) { for (int col = 0; col < lines.get(row).length(); col++) { char nextNumber = lines.get(row).charAt(col); if ('0' <= nextNumber && nextNumber <= '9') { grid[row][col] = nextNumber - '0'; } } } return grid; } }
6,635
28.362832
98
java
java-smt
java-smt-master/doc/Example-Gradle-Project/src/main/java/org/sosy_lab/java_smt_example/SolverOverviewTable.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_example; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.SolverOverviewTable.RowBuilder; import org.sosy_lab.java_smt.example.SolverOverviewTable.SolverInfo; /** * This program takes all installed solvers and checks them for version, theories and features and * prints them to StdOut in a nice table. * * <p>This is just using org.sosy_lab.java_smt.example.SolverOverviewTable */ public class SolverOverviewTable { public static void main(String[] args) throws SolverException, InterruptedException { final org.sosy_lab.java_smt.example.SolverOverviewTable infoProvider = new org.sosy_lab.java_smt.example.SolverOverviewTable(); final List<SolverInfo> infos = new ArrayList<>(); for (Solvers s : Solvers.values()) { infos.add(infoProvider.getSolverInformation(s)); } infos.sort(Comparator.comparing(SolverInfo::getName)); // alphabetical ordering RowBuilder rowBuilder = new RowBuilder(); for (SolverInfo info : infos) { rowBuilder.addSolver(info); } System.out.println(rowBuilder); } private SolverOverviewTable() {} }
1,544
31.87234
98
java
java-smt
java-smt-master/doc/Example-Gradle-Project/src/test/java/org/sosy_lab/java_smt_example/SudokuTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_example; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.sosy_lab.java_smt.example.Sudoku.SIZE; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.log.BasicLogManager; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.Sudoku.IntegerBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.BooleanBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.SudokuSolver; /** * This program parses a String-given Sudoku and solves it with an SMT solver. * * <p>This program is just an example and clearly SMT is not the best solution for solving Sudoku. * There might be other algorithms out there that are better suited for solving Sudoku. * * <p>The more numbers are available in a Sudoku, the easier it can be solved. A completely empty * Sudoku will cause the longest runtime in the solver, because it will guess a lot of values. * * <p>The Sudoku is read from a String and should be formatted as the following example: * * <pre> * 2..9.6..1 * ..6.4...9 * ...52.4.. * 3.2..7.5. * ...2..1.. * .9.3..7.. * .87.5.31. * 6.3.1.8.. * 4....9... * </pre> * * <p>The solution will then be printed on StdOut and checked by an assertion, just like the * following solution: * * <pre> * 248976531 * 536148279 * 179523468 * 312487956 * 764295183 * 895361742 * 987652314 * 623714895 * 451839627 * </pre> */ public class SudokuTest { private Configuration config; private LogManager logger; private ShutdownNotifier notifier; private SolverContext context; private static final String input = "2..9.6..1\n" + "..6.4...9\n" + "...52.4..\n" + "3.2..7.5.\n" + "...2..1..\n" + ".9.3..7..\n" + ".87.5.31.\n" + "6.3.1.8..\n" + "4....9..."; private static final String sudokuSolution = "248976531\n" + "536148279\n" + "179523468\n" + "312487956\n" + "764295183\n" + "895361742\n" + "987652314\n" + "623714895\n" + "451839627\n"; @Before public void init() throws InvalidConfigurationException { config = Configuration.defaultConfiguration(); logger = BasicLogManager.create(config); notifier = ShutdownNotifier.createDummy(); } /* * We close our context after we are done with a solver to not waste memory. */ @After public final void closeSolver() { if (context != null) { context.close(); } } @Test public void princessSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.PRINCESS); } @Test public void smtInterpolSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.SMTINTERPOL); } @Test public void cvc4SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.CVC4); } @Test public void z3SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.Z3); } @Test public void mathsatSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.MATHSAT5); } @Test public void boolectorSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { // Boolector does not support Integers checkSudokuWithBooleans(Solvers.BOOLECTOR); } @Test public void yicesSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.YICES2); } private void checkSudoku(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new IntegerBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } // Same as checkSudoku but with Booleans instead of Integers private void checkSudokuWithBooleans(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new BooleanBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } private String solutionToString(Integer[][] solution) { StringBuilder sb = new StringBuilder(); for (Integer[] s1 : solution) { sb.append(Joiner.on("").join(s1)).append('\n'); } return sb.toString(); } /** * a simple parser for a half-filled Sudoku. * * <p>Use digits 0-9 as values, other values will be set to 'unknown'. */ private Integer[][] readGridFromString(String puzzle) { Integer[][] grid = new Integer[SIZE][SIZE]; List<String> lines = Splitter.on('\n').splitToList(puzzle); for (int row = 0; row < lines.size(); row++) { for (int col = 0; col < lines.get(row).length(); col++) { char nextNumber = lines.get(row).charAt(col); if ('0' <= nextNumber && nextNumber <= '9') { grid[row][col] = nextNumber - '0'; } } } return grid; } }
6,455
28.751152
98
java
java-smt
java-smt-master/doc/Example-Maven-Project/src/main/java/org/sosy_lab/java_smt_example/SolverOverviewTable.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_example; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.SolverOverviewTable.RowBuilder; import org.sosy_lab.java_smt.example.SolverOverviewTable.SolverInfo; /** * This program takes all installed solvers and checks them for version, theories and features and * prints them to StdOut in a nice table. * * <p>This is just a copy of org.sosy_lab.java_smt.example.SolverOverviewTable */ public class SolverOverviewTable { public static void main(String[] args) throws SolverException, InterruptedException { final org.sosy_lab.java_smt.example.SolverOverviewTable infoProvider = new org.sosy_lab.java_smt.example.SolverOverviewTable(); final List<SolverInfo> infos = new ArrayList<>(); for (Solvers s : Solvers.values()) { infos.add(infoProvider.getSolverInformation(s)); } infos.sort(Comparator.comparing(SolverInfo::getName)); // alphabetical ordering RowBuilder rowBuilder = new RowBuilder(); for (SolverInfo info : infos) { rowBuilder.addSolver(info); } System.out.println(rowBuilder); } private SolverOverviewTable() {} }
1,546
31.914894
98
java
java-smt
java-smt-master/doc/Example-Maven-Project/src/test/java/org/sosy_lab/java_smt_example/SudokuTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_example; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assume.assumeTrue; import static org.sosy_lab.java_smt.example.Sudoku.SIZE; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.log.BasicLogManager; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.Sudoku.IntegerBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.SudokuSolver; /** * This program parses a String-given Sudoku and solves it with an SMT solver. * * <p>This program is just an example and clearly SMT is not the best solution for solving Sudoku. * There might be other algorithms out there that are better suited for solving Sudoku. * * <p>The more numbers are available in a Sudoku, the easier it can be solved. A completely empty * Sudoku will cause the longest runtime in the solver, because it will guess a lot of values. * * <p>The Sudoku is read from a String and should be formatted as the following example: * * <pre> * 2..9.6..1 * ..6.4...9 * ...52.4.. * 3.2..7.5. * ...2..1.. * .9.3..7.. * .87.5.31. * 6.3.1.8.. * 4....9... * </pre> * * <p>The solution will then be printed on StdOut and checked by an assertion, just like the * following solution: * * <pre> * 248976531 * 536148279 * 179523468 * 312487956 * 764295183 * 895361742 * 987652314 * 623714895 * 451839627 * </pre> */ public class SudokuTest { private static final String OS = System.getProperty("os.name").toLowerCase().replace(" ", ""); private static final boolean IS_WINDOWS = OS.startsWith("windows"); private static final boolean IS_MAC = OS.startsWith("macos"); private static final boolean IS_LINUX = OS.startsWith("linux"); /** * Let's allow to disable some checks on certain combinations of operating systems and solvers, * because of missing support. * * <p>We update this list, whenever a new solver or operating system is added. */ private static boolean isOperatingSystemSupported(Solvers solver) { switch (solver) { case SMTINTERPOL: case PRINCESS: // any operating system is allowed, Java is already available. return true; case BOOLECTOR: case CVC4: case YICES2: return IS_LINUX; case MATHSAT5: return IS_LINUX || IS_WINDOWS; case Z3: return IS_LINUX || IS_WINDOWS || IS_MAC; default: throw new AssertionError("unexpected solver: " + solver); } } private Configuration config; private LogManager logger; private ShutdownNotifier notifier; private SolverContext context; private static final String input = "2..9.6..1\n" + "..6.4...9\n" + "...52.4..\n" + "3.2..7.5.\n" + "...2..1..\n" + ".9.3..7..\n" + ".87.5.31.\n" + "6.3.1.8..\n" + "4....9..."; private static final String sudokuSolution = "248976531\n" + "536148279\n" + "179523468\n" + "312487956\n" + "764295183\n" + "895361742\n" + "987652314\n" + "623714895\n" + "451839627\n"; @Before public void init() throws InvalidConfigurationException { config = Configuration.defaultConfiguration(); logger = BasicLogManager.create(config); notifier = ShutdownNotifier.createDummy(); } /* * We close our context after we are done with a solver to not waste memory. */ @After public final void closeSolver() { if (context != null) { context.close(); } } @Test public void princessSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.PRINCESS); } @Test public void z3SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.Z3); } @Test public void mathsatSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.MATHSAT5); } @Test public void boolectorSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { // Boolector does not support Integer logic // checkSudoku(Solvers.BOOLECTOR); } @Test public void cvc4SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.CVC4); } @Test public void yices2SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.YICES2); } private void checkSudoku(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { assumeTrue(isOperatingSystemSupported(solver)); context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new IntegerBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } private String solutionToString(Integer[][] solution) { StringBuilder sb = new StringBuilder(); for (Integer[] s1 : solution) { sb.append(Joiner.on("").join(s1)).append('\n'); } return sb.toString(); } /** * a simple parser for a half-filled Sudoku. * * <p>Use digits 0-9 as values, other values will be set to 'unknown'. */ private Integer[][] readGridFromString(String puzzle) { Integer[][] grid = new Integer[SIZE][SIZE]; List<String> lines = Splitter.on('\n').splitToList(puzzle); for (int row = 0; row < lines.size(); row++) { for (int col = 0; col < lines.get(row).length(); col++) { char nextNumber = lines.get(row).charAt(col); if ('0' <= nextNumber && nextNumber <= '9') { grid[row][col] = nextNumber - '0'; } } } return grid; } }
6,795
28.807018
98
java
java-smt
java-smt-master/doc/Example-Maven-Web-Project/src/main/java/org/sosy_lab/SolverOverviewServlet.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.SolverOverviewTable.RowBuilder; import org.sosy_lab.java_smt.example.SolverOverviewTable.SolverInfo; /** Servlet implementation class SolverOverviewServlet */ @WebServlet("/SolverOverviewServlet") public class SolverOverviewServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** @see HttpServlet#HttpServlet() */ public SolverOverviewServlet() { super(); } /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); response.getWriter().println("\nThis is a test for JavaSMT.\n"); try { SolverInfoPrinter printer = new SolverInfoPrinter(); printer.printSolverInformation(response.getWriter()); } catch (Exception e) { response.getWriter().println("\nException"); response.getWriter().println(e.getMessage()); } } /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public class SolverInfoPrinter { public void printSolverInformation(PrintWriter out) throws InterruptedException, SolverException { final org.sosy_lab.java_smt.example.SolverOverviewTable infoProvider = new org.sosy_lab.java_smt.example.SolverOverviewTable(); final List<SolverInfo> infos = new ArrayList<>(); for (Solvers s : Solvers.values()) { infos.add(infoProvider.getSolverInformation(s)); } infos.sort(Comparator.comparing(SolverInfo::getName)); // alphabetical ordering RowBuilder rowBuilder = new RowBuilder(); for (SolverInfo info : infos) { rowBuilder.addSolver(info); } out.println(rowBuilder); } } }
2,770
33.209877
90
java
java-smt
java-smt-master/doc/Example-Maven-Web-Project/src/test/java/org/sosy_lab/java_smt_web_example/SudokuTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt_web_example; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assume.assumeTrue; import static org.sosy_lab.java_smt.example.Sudoku.SIZE; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.log.BasicLogManager; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.example.Sudoku.IntegerBasedSudokuSolver; import org.sosy_lab.java_smt.example.Sudoku.SudokuSolver; /** * This program parses a String-given Sudoku and solves it with an SMT solver. * * <p>This program is just an example and clearly SMT is not the best solution for solving Sudoku. * There might be other algorithms out there that are better suited for solving Sudoku. * * <p>The more numbers are available in a Sudoku, the easier it can be solved. A completely empty * Sudoku will cause the longest runtime in the solver, because it will guess a lot of values. * * <p>The Sudoku is read from a String and should be formatted as the following example: * * <pre> * 2..9.6..1 * ..6.4...9 * ...52.4.. * 3.2..7.5. * ...2..1.. * .9.3..7.. * .87.5.31. * 6.3.1.8.. * 4....9... * </pre> * * <p>The solution will then be printed on StdOut and checked by an assertion, just like the * following solution: * * <pre> * 248976531 * 536148279 * 179523468 * 312487956 * 764295183 * 895361742 * 987652314 * 623714895 * 451839627 * </pre> */ public class SudokuTest { private static final String OS = System.getProperty("os.name").toLowerCase().replace(" ", ""); private static final boolean IS_WINDOWS = OS.startsWith("windows"); private static final boolean IS_MAC = OS.startsWith("macos"); private static final boolean IS_LINUX = OS.startsWith("linux"); /** * Let's allow to disable some checks on certain combinations of operating systems and solvers, * because of missing support. * * <p>We update this list, whenever a new solver or operating system is added. */ private static boolean isOperatingSystemSupported(Solvers solver) { switch (solver) { case SMTINTERPOL: case PRINCESS: // any operating system is allowed, Java is already available. return true; case BOOLECTOR: case CVC4: case YICES2: return IS_LINUX; case MATHSAT5: return IS_LINUX || IS_WINDOWS; case Z3: return IS_LINUX || IS_WINDOWS || IS_MAC; default: throw new AssertionError("unexpected solver: " + solver); } } private Configuration config; private LogManager logger; private ShutdownNotifier notifier; private SolverContext context; private static final String input = "2..9.6..1\n" + "..6.4...9\n" + "...52.4..\n" + "3.2..7.5.\n" + "...2..1..\n" + ".9.3..7..\n" + ".87.5.31.\n" + "6.3.1.8..\n" + "4....9..."; private static final String sudokuSolution = "248976531\n" + "536148279\n" + "179523468\n" + "312487956\n" + "764295183\n" + "895361742\n" + "987652314\n" + "623714895\n" + "451839627\n"; @Before public void init() throws InvalidConfigurationException { config = Configuration.defaultConfiguration(); logger = BasicLogManager.create(config); notifier = ShutdownNotifier.createDummy(); } /* * We close our context after we are done with a solver to not waste memory. */ @After public final void closeSolver() { if (context != null) { context.close(); } } @Test public void princessSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.PRINCESS); } @Test public void z3SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.Z3); } @Test public void mathsatSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.MATHSAT5); } @Test public void boolectorSudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { // Boolector does not support Integer logic // checkSudoku(Solvers.BOOLECTOR); } @Test public void cvc4SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.CVC4); } @Test public void yices2SudokuTest() throws InvalidConfigurationException, InterruptedException, SolverException { checkSudoku(Solvers.YICES2); } private void checkSudoku(Solvers solver) throws InvalidConfigurationException, InterruptedException, SolverException { assumeTrue(isOperatingSystemSupported(solver)); context = SolverContextFactory.createSolverContext(config, logger, notifier, solver); Integer[][] grid = readGridFromString(input); SudokuSolver<?> sudoku = new IntegerBasedSudokuSolver(context); Integer[][] solution = sudoku.solve(grid); assertNotNull(solution); assertEquals(sudokuSolution, solutionToString(solution)); } private String solutionToString(Integer[][] solution) { StringBuilder sb = new StringBuilder(); for (Integer[] s1 : solution) { sb.append(Joiner.on("").join(s1)).append('\n'); } return sb.toString(); } /** * a simple parser for a half-filled Sudoku. * * <p>Use digits 0-9 as values, other values will be set to 'unknown'. */ private Integer[][] readGridFromString(String puzzle) { Integer[][] grid = new Integer[SIZE][SIZE]; List<String> lines = Splitter.on('\n').splitToList(puzzle); for (int row = 0; row < lines.size(); row++) { for (int col = 0; col < lines.get(row).length(); col++) { char nextNumber = lines.get(row).charAt(col); if ('0' <= nextNumber && nextNumber <= '9') { grid[row][col] = nextNumber - '0'; } } } return grid; } }
6,799
28.824561
98
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/PackageSanityTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt; import com.google.common.testing.AbstractPackageSanityTests; import org.sosy_lab.common.ShutdownManager; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; public class PackageSanityTest extends AbstractPackageSanityTests { { setDefault(Configuration.class, Configuration.defaultConfiguration()); setDefault(ShutdownNotifier.class, ShutdownManager.create().getNotifier()); } }
713
30.043478
79
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/SolverContextFactory.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt; import static com.google.common.base.Preconditions.checkNotNull; import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Consumer; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.NativeLibraries; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.FileOption; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.configuration.Option; import org.sosy_lab.common.configuration.Options; import org.sosy_lab.common.io.PathCounterTemplate; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.api.FloatingPointRoundingMode; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.basicimpl.AbstractNumeralFormulaManager.NonLinearArithmetic; import org.sosy_lab.java_smt.delegate.logging.LoggingSolverContext; import org.sosy_lab.java_smt.delegate.statistics.StatisticsSolverContext; import org.sosy_lab.java_smt.delegate.synchronize.SynchronizedSolverContext; import org.sosy_lab.java_smt.solvers.boolector.BoolectorSolverContext; import org.sosy_lab.java_smt.solvers.cvc4.CVC4SolverContext; import org.sosy_lab.java_smt.solvers.cvc5.CVC5SolverContext; import org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5SolverContext; import org.sosy_lab.java_smt.solvers.princess.PrincessSolverContext; import org.sosy_lab.java_smt.solvers.smtinterpol.SmtInterpolSolverContext; import org.sosy_lab.java_smt.solvers.yices2.Yices2SolverContext; import org.sosy_lab.java_smt.solvers.z3.Z3SolverContext; /** * Factory class for loading and generating solver contexts. Generates a {@link SolverContext} * corresponding to the chosen solver. * * <p>Main entry point for JavaSMT. */ @Options(prefix = "solver") public class SolverContextFactory { public enum Solvers { MATHSAT5, SMTINTERPOL, Z3, PRINCESS, BOOLECTOR, CVC4, CVC5, YICES2 } @Option(secure = true, description = "Export solver queries in SmtLib format into a file.") private boolean logAllQueries = false; @Option(secure = true, description = "Export solver queries in SmtLib format into a file.") @FileOption(FileOption.Type.OUTPUT_FILE) private @Nullable PathCounterTemplate logfile = PathCounterTemplate.ofFormatString("smtquery.%03d.smt2"); @Option( secure = true, description = "If logging from the same application, avoid conflicting logfile names.") private boolean renameLogfileToAvoidConflicts = true; private static final Set<String> logfiles = new LinkedHashSet<>(); @Option(secure = true, description = "Random seed for SMT solver.") private long randomSeed = 42; @Option(secure = true, description = "Which SMT solver to use.") private Solvers solver = Solvers.SMTINTERPOL; @Option(secure = true, description = "Log solver actions, this may be slow!") private boolean useLogger = false; @Option( secure = true, description = "Sequentialize all solver actions to allow concurrent access!") private boolean synchronize = false; @Option( secure = true, description = "Counts all operations and interactions towards the SMT solver.") private boolean collectStatistics = false; @Option(secure = true, description = "Default rounding mode for floating point operations.") private FloatingPointRoundingMode floatingPointRoundingMode = FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN; @Option( secure = true, description = "Use non-linear arithmetic of the solver if supported and throw exception otherwise, " + "approximate non-linear arithmetic with UFs if unsupported, " + "or always approximate non-linear arithmetic. " + "This affects only the theories of integer and rational arithmetic.") private NonLinearArithmetic nonLinearArithmetic = NonLinearArithmetic.USE; private final LogManager logger; private final ShutdownNotifier shutdownNotifier; private final Configuration config; private final Consumer<String> loader; /** * This constructor uses the default JavaSMT loader for accessing native libraries. * * @see #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer) */ public SolverContextFactory( Configuration pConfig, LogManager pLogger, ShutdownNotifier pShutdownNotifier) throws InvalidConfigurationException { this(pConfig, pLogger, pShutdownNotifier, NativeLibraries::loadLibrary); } /** * This constructor instantiates a factory for building solver contexts for a configured SMT * solver (via the parameter <code>pConfig</code>). Each created context is independent of other * contexts and uses its own environment for building formulas and querying the solver. * * @param pConfig The configuration to be used when instantiating JavaSMT and the solvers. By * default, the configuration specifies the solver to use via the option <code> * solver.solver=...</code>. This option can be overridden when calling the method {@link * #generateContext(Solvers)}. * @param pLogger The processing of log messages from SMT solvers (or their bindings) is handled * via this LogManager. * @param pShutdownNotifier This central instance allows to request the termination of all * operations in the created solver. Please note that the solver can decide on its own to * accept the shutdown request and terminate its operation afterwards. We do not forcefully * terminate any solver query eagerly. In general, a solver is of good nature, and maturely * developed, and terminates accordingly. * @param pLoader The loading mechanism (loading method) in this class can be injected by the user * and, e.g., can be used to search for the library binaries in more directories. This makes * the loading process for native solvers like Boolector, CVC4, MathSAT, Z3 more flexible. For * Java-based libraries (solvers like SMTInterpol or Princess, and also other dependences), * this class is irrelevant and not accessed. */ public SolverContextFactory( Configuration pConfig, LogManager pLogger, ShutdownNotifier pShutdownNotifier, Consumer<String> pLoader) throws InvalidConfigurationException { pConfig.inject(this); logger = pLogger.withComponentName("JavaSMT"); shutdownNotifier = checkNotNull(pShutdownNotifier); config = pConfig; loader = checkNotNull(pLoader); if (!logAllQueries) { logfile = null; } if (logfile != null && renameLogfileToAvoidConflicts) { logfile = makeUniqueLogfile(logfile); } } /** * compute a new unused template. This method is helpful, if several instances of a solver are * used interleaved via JavaSMT and only one configuration is used. */ private static synchronized PathCounterTemplate makeUniqueLogfile(PathCounterTemplate pLogfile) { final String original = pLogfile.getTemplate(); final String extension = getFileExtension(original); final String basename = original.substring(0, original.length() - extension.length()); String template = original; int counter = 0; while (logfiles.contains(template)) { counter++; template = basename + "." + counter + extension; } logfiles.add(template); return PathCounterTemplate.ofFormatString(template); } private static String getFileExtension(String path) { int lastIndexOf = path.lastIndexOf('.'); return (lastIndexOf == -1) ? "" : path.substring(lastIndexOf); } /** Create new context with solver chosen according to the supplied configuration. */ public SolverContext generateContext() throws InvalidConfigurationException { return generateContext(solver); } /** * Create new context with solver name supplied. * * @see #generateContext() */ @SuppressWarnings("resource") // returns unclosed context object public SolverContext generateContext(Solvers solverToCreate) throws InvalidConfigurationException { SolverContext context; try { context = generateContext0(solverToCreate); } catch (UnsatisfiedLinkError | NoClassDefFoundError e) { throw new InvalidConfigurationException( String.format( "The SMT solver %s is not available on this machine because of missing libraries" + " (%s).", solverToCreate, e.getMessage()), e); } if (useLogger) { context = new LoggingSolverContext(logger, context); } if (synchronize) { context = new SynchronizedSolverContext(config, logger, shutdownNotifier, context); } if (collectStatistics) { // statistics need to be the most outer wrapping layer. context = new StatisticsSolverContext(context); } return context; } private SolverContext generateContext0(Solvers solverToCreate) throws InvalidConfigurationException { switch (solverToCreate) { case CVC4: return CVC4SolverContext.create( logger, shutdownNotifier, (int) randomSeed, nonLinearArithmetic, floatingPointRoundingMode, loader); case CVC5: return CVC5SolverContext.create( logger, shutdownNotifier, (int) randomSeed, nonLinearArithmetic, floatingPointRoundingMode, loader); case SMTINTERPOL: return SmtInterpolSolverContext.create( config, logger, shutdownNotifier, logfile, randomSeed, nonLinearArithmetic); case MATHSAT5: return Mathsat5SolverContext.create( logger, config, shutdownNotifier, logfile, randomSeed, floatingPointRoundingMode, nonLinearArithmetic, loader); case Z3: return Z3SolverContext.create( logger, config, shutdownNotifier, logfile, randomSeed, floatingPointRoundingMode, nonLinearArithmetic, loader); case PRINCESS: return PrincessSolverContext.create( config, shutdownNotifier, logfile, (int) randomSeed, nonLinearArithmetic); case YICES2: return Yices2SolverContext.create(nonLinearArithmetic, shutdownNotifier, loader); case BOOLECTOR: return BoolectorSolverContext.create(config, shutdownNotifier, logfile, randomSeed, loader); default: throw new AssertionError("no solver selected"); } } /** * Shortcut for getting a {@link SolverContext}, the solver is selected using the configuration * {@code config}. */ public static SolverContext createSolverContext( Configuration config, LogManager logger, ShutdownNotifier shutdownNotifier) throws InvalidConfigurationException { return new SolverContextFactory(config, logger, shutdownNotifier, NativeLibraries::loadLibrary) .generateContext(); } /** * Shortcut for getting a {@link SolverContext}, the solver is selected using an argument. * * <p>See {@link #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer)} for * documentation of accepted parameters. */ public static SolverContext createSolverContext( Configuration config, LogManager logger, ShutdownNotifier shutdownNotifier, Solvers solver) throws InvalidConfigurationException { return new SolverContextFactory(config, logger, shutdownNotifier, NativeLibraries::loadLibrary) .generateContext(solver); } /** * This is the most explicit method for getting a {@link SolverContext}, the solver, the logger, * the shutdownNotifier, and the libraryLoader are provided as parameters by the caller. * * <p>See {@link #SolverContextFactory(Configuration, LogManager, ShutdownNotifier, Consumer)} for * documentation of accepted parameters. */ public static SolverContext createSolverContext( Configuration config, LogManager logger, ShutdownNotifier shutdownNotifier, Solvers solver, Consumer<String> loader) throws InvalidConfigurationException { return new SolverContextFactory(config, logger, shutdownNotifier, loader) .generateContext(solver); } /** * Minimalistic shortcut for creating a solver context. Empty default configuration, no logging, * and no shutdown notifier. * * @param solver Solver to initialize */ public static SolverContext createSolverContext(Solvers solver) throws InvalidConfigurationException { return new SolverContextFactory( Configuration.defaultConfiguration(), LogManager.createNullLogManager(), ShutdownNotifier.createDummy(), NativeLibraries::loadLibrary) .generateContext(solver); } }
13,297
37.212644
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** * JavaSMT: a generic SMT solver API. * * <p>{@link org.sosy_lab.java_smt.SolverContextFactory} is a package entry point, which creates a * {@link org.sosy_lab.java_smt.api.SolverContext} object. All operations on formulas are performed * using managers, available through the context object. * * <p>All interfaces which form the public API are located in the <a * href="api/package-summary.html">API package</a>. */ @com.google.errorprone.annotations.CheckReturnValue @javax.annotation.ParametersAreNonnullByDefault @org.sosy_lab.common.annotations.FieldsAreNonnullByDefault @org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault package org.sosy_lab.java_smt;
924
37.541667
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/ArrayFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** * A formula of the array sort. * * @param <TI> Index type. * @param <TE> Element type. */ @Immutable public interface ArrayFormula<TI extends Formula, TE extends Formula> extends Formula {}
528
24.190476
88
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/ArrayFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; /** * This interface represents the theory of (arbitrarily nested) arrays. (as defined in the SMTLIB2 * standard) */ @SuppressWarnings("MethodTypeParameterName") public interface ArrayFormulaManager { /** * Read a value that is stored in the array at the specified position. * * @param pArray The array from which to read * @param pIndex The position from which to read * @return A formula that represents the result of the "read" */ <TI extends Formula, TE extends Formula> TE select(ArrayFormula<TI, TE> pArray, TI pIndex); /** * Store a value into a cell of the specified array. * * @param pArray The array to which to write * @param pIndex The position to which to write * @param pValue The value that should be written * @return A formula that represents the "write" */ <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> store( ArrayFormula<TI, TE> pArray, TI pIndex, TE pValue); /** * Declare a new array with exactly the given name. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. * * @param pIndexType The type of the array index * @param pElementType The type of the array elements * @return Formula that represents the array */ <TI extends Formula, TE extends Formula, FTI extends FormulaType<TI>, FTE extends FormulaType<TE>> ArrayFormula<TI, TE> makeArray(String pName, FTI pIndexType, FTE pElementType); /** * Declare a new array. * * @param pName The name of the array variable */ <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> makeArray( String pName, ArrayFormulaType<TI, TE> type); /** Make a {@link BooleanFormula} that represents the equality of two {@link ArrayFormula}. */ <TI extends Formula, TE extends Formula> BooleanFormula equivalence( ArrayFormula<TI, TE> pArray1, ArrayFormula<TI, TE> pArray2); <TI extends Formula> FormulaType<TI> getIndexType(ArrayFormula<TI, ?> pArray); <TE extends Formula> FormulaType<TE> getElementType(ArrayFormula<?, TE> pArray); }
2,663
36
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/BasicProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.java_smt.api.SolverContext.ProverOptions; /** * Super interface for {@link ProverEnvironment} and {@link InterpolatingProverEnvironment} that * provides only the common operations. In most cases, just use one of the two sub-interfaces */ public interface BasicProverEnvironment<T> extends AutoCloseable { String NO_MODEL_HELP = "Model computation failed. Are the pushed formulae satisfiable?"; /** * Push a backtracking point and add a formula to the current stack, asserting it. The return * value may be used to identify this formula later on in a query (this depends on the sub-type of * the environment). */ @Nullable @CanIgnoreReturnValue default T push(BooleanFormula f) throws InterruptedException { push(); return addConstraint(f); } /** * Remove one backtracking point/level from the current stack. This removes the latest level * including all of its formulas, i.e., all formulas that were added for this backtracking point. */ void pop(); /** Add a constraint to the latest backtracking point. */ @Nullable @CanIgnoreReturnValue T addConstraint(BooleanFormula constraint) throws InterruptedException; /** * Create a new backtracking point, i.e., a new level on the assertion stack. Each level can hold * several asserted formulas. * * <p>If formulas are added before creating the first backtracking point, they can not be removed * via a POP-operation. */ void push() throws InterruptedException; /** * Get the number of backtracking points/levels on the current stack. * * <p>Caution: This is the number of PUSH-operations, and not necessarily equal to the number of * asserted formulas. On any level there can be an arbitrary number of asserted formulas. Even * with size of 0, formulas can already be asserted (at bottom level). */ int size(); /** Check whether the conjunction of all formulas on the stack is unsatisfiable. */ boolean isUnsat() throws SolverException, InterruptedException; /** * Check whether the conjunction of all formulas on the stack together with the list of * assumptions is satisfiable. * * @param assumptions A list of literals. */ boolean isUnsatWithAssumptions(Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException; /** * Get a satisfying assignment. This method should be called only immediately after an {@link * #isUnsat()} call that returned <code>false</code>. The returned model is guaranteed to stay * constant and valid as long as the solver context is available, even if constraints are added * to, pushed or popped from the prover stack. * * <p>A model might contain additional symbols with their evaluation, if a solver uses its own * temporary symbols. There should be at least a value-assignment for each free symbol. */ Model getModel() throws SolverException; /** * Get a temporary view on the current satisfying assignment. This should be called only * immediately after an {@link #isUnsat()} call that returned <code>false</code>. The evaluator * should no longer be used as soon as any constraints are added to, pushed, or popped from the * prover stack. */ default Evaluator getEvaluator() throws SolverException { return getModel(); } /** * Get a list of satisfying assignments. This is equivalent to <code> * ImmutableList.copyOf(getModel())</code>, but removes the need for calling {@link * Model#close()}. * * <p>Note that if you need to iterate multiple times over the model it may be more efficient to * use this method instead of {@link #getModel()} (depending on the solver). */ default ImmutableList<Model.ValueAssignment> getModelAssignments() throws SolverException { try (Model model = getModel()) { return model.asList(); } } /** * Get an unsat core. This should be called only immediately after an {@link #isUnsat()} call that * returned <code>false</code>. */ List<BooleanFormula> getUnsatCore(); /** * Returns an UNSAT core (if it exists, otherwise {@code Optional.empty()}), over the chosen * assumptions. Does NOT require the {@link ProverOptions#GENERATE_UNSAT_CORE} option to work. * * @param assumptions Selected assumptions * @return Empty optional if the constraints with assumptions are satisfiable, subset of * assumptions which is unsatisfiable with the original constraints otherwise. */ Optional<List<BooleanFormula>> unsatCoreOverAssumptions(Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException; /** * Get statistics for a concrete ProverEnvironment in a solver. The returned mapping is intended * to provide solver-internal statistics for only this instance. The keys can differ between * individual solvers. * * <p>Calling the statistics several times for the same {@link ProverEnvironment}s returns * accumulated number, i.e., we currently do not provide any possibility to reset the statistics. * Calling the statistics for different {@link ProverEnvironment}s returns independent statistics. * * <p>We do not guarantee any specific key to be present, as this depends on the used solver. We * might even return an empty mapping if the solver does not support calling this method or is in * an invalid state. * * @see SolverContext#getStatistics() */ default ImmutableMap<String, String> getStatistics() { return ImmutableMap.of(); } /** * Closes the prover environment. The object should be discarded, and should not be used after * closing. The first call of this method will close the prover instance, further calls are * ignored. */ @Override void close(); /** * Get all satisfying assignments of the current environment with regard to a subset of terms, and * create a region representing all those models. * * @param important A set of (positive) variables appearing in the asserted queries. Only these * variables will appear in the region. * @return A region representing all satisfying models of the formula. */ <R> R allSat(AllSatCallback<R> callback, List<BooleanFormula> important) throws InterruptedException, SolverException; /** * Interface for the {@link #allSat} callback. * * @param <R> The result type of the callback, passed through by {@link #allSat}. */ interface AllSatCallback<R> { /** * Callback for each possible satisfying assignment to given {@code important} predicates. If * the predicate is assigned {@code true} in the model, it is returned as-is in the list, and * otherwise it is negated. * * <p>There is no guarantee that the list of model values corresponds to the list in {@link * BasicProverEnvironment#allSat}. We can reorder the variables or leave out values with a * freely chosen value. */ void apply(List<BooleanFormula> model); /** Returning the result generated after all the {@link #apply} calls went through. */ R getResult() throws InterruptedException; } }
7,726
39.036269
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/BitvectorFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** A formula of the bitvector sort. */ @Immutable public interface BitvectorFormula extends Formula {}
433
26.125
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/BitvectorFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.math.BigInteger; import java.util.List; import org.sosy_lab.java_smt.api.FormulaType.BitvectorType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; /** Manager for dealing with formulas of the bitvector sort. */ public interface BitvectorFormulaManager { /** * Convert a number into a bitvector with given size. * * @throws IllegalArgumentException if the number is out of range for the given length. */ BitvectorFormula makeBitvector(int length, long pI); /** * Convert a number into a bitvector with given size. * * @throws IllegalArgumentException if the number is out of range for the given length. */ BitvectorFormula makeBitvector(int length, BigInteger pI); /** * Convert/Cast/Interpret a numeral formula into a bitvector with given size. * * <p>If the numeral formula is too large for the given length, we cut off the largest bits and * only use the lest significant bits. */ BitvectorFormula makeBitvector(int length, IntegerFormula pI); /** Convert/Cast/Interpret a signed/unsigned bitvector formula as an integer formula. */ IntegerFormula toIntegerFormula(BitvectorFormula pI, boolean signed); /** * Creates a variable with exactly the given name and bitwidth. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ BitvectorFormula makeVariable(int length, String pVar); /** * @see #makeVariable(int, String) */ BitvectorFormula makeVariable(BitvectorType type, String pVar); /** This method returns the length of a bitvector, also denoted as bit-size. */ int getLength(BitvectorFormula number); // Numeric Operations /** * This method returns the negated number, i.e., it is multiplied by "-1". The given number is * interpreted as signed bitvector and corresponds to "2^BITSIZE - number". The result has the * same length as the given number. */ BitvectorFormula negate(BitvectorFormula number); /** * This method returns the addition of the given bitvectors. The result has the same length as the * given parameters. There can be an overflow, i.e., as one would expect from bitvector logic. * There is no difference in signed and unsigned numbers. * * @param number1 a Formula * @param number2 a Formula * @return {@code number1 + number2} */ BitvectorFormula add(BitvectorFormula number1, BitvectorFormula number2); /** * This method returns the subtraction of the given bitvectors. The result has the same length as * the given parameters. There can be an overflow, i.e., as one would expect from bitvector logic. * There is no difference in signed and unsigned numbers. * * @param number1 a Formula * @param number2 a Formula * @return {@code number1 - number2} */ BitvectorFormula subtract(BitvectorFormula number1, BitvectorFormula number2); /** * This method returns the division for two bitvector formulas. * * <p>For signed bitvectors, the result is rounded towards zero (also called "truncated integer * division", similar to the division in the C99 standard), e.g., a user can assume the following * equations: * * <ul> * <li>10 / 5 = 2 * <li>10 / 3 = 3 * <li>10 / (-3) = -3 * <li>-10 / 5 = -2 * <li>-10 / 3 = -3 * <li>-10 / (-3) = 3 * </ul> * * <p>If the denumerator evaluates to zero (division-by-zero), either directly as value or * indirectly via an additional constraint, then the result of the division is defined as: * * <ul> * <li>"-1" interpreted as bitvector (i.e., all bits set to "1"), if the numerator is * non-negative, and * <li>"1" interpreted as bitvector (i.e., all bits set to "0", except the last bit), if the * numerator is negative. * </ul> * * <p>We refer to the SMTLIB standard for the division and modulo operators in BV theory. * * @param numerator dividend * @param denumerator divisor * @param signed whether to interpret all operands as signed or as unsigned numbers. */ BitvectorFormula divide(BitvectorFormula numerator, BitvectorFormula denumerator, boolean signed); /** * This method returns the remainder (modulo) for two bitvector formulas. * * <p>For signed bitvectors, the sign of the result follows the sign of the numerator, e.g., a * user can assume the following equations: * * <ul> * <li>10 % 5 = 0 * <li>10 % 3 = 1 * <li>10 % (-3) = 1 * <li>-10 % 5 = 0 * <li>-10 % 3 = -1 * <li>-10 % (-3) = -1 * </ul> * * <p>If the denumerator evaluates to zero (modulo-by-zero), either directly as value or * indirectly via an additional constraint, then the result of the modulo operation is defined as * the numerator itself. We refer to the SMTLIB standard for the division and modulo operators in * BV theory. * * @param numerator dividend * @param denumerator divisor * @param signed whether to interpret all operands as signed or as unsigned numbers. */ BitvectorFormula modulo(BitvectorFormula numerator, BitvectorFormula denumerator, boolean signed); /** * This method returns the multiplication of the given bitvectors. The result has the same length * as the given parameters. There can be an overflow, i.e., as one would expect from bitvector * logic. There is no difference in signed and unsigned numbers. * * @param number1 a Formula * @param number2 a Formula * @return {@code number1 - number2} */ BitvectorFormula multiply(BitvectorFormula number1, BitvectorFormula number2); // ----------------- Numeric relations ----------------- /** * This method returns the bit-wise equality of the given bitvectors. * * @param number1 a Formula * @param number2 a Formula * @return {@code number1 == number2} */ BooleanFormula equal(BitvectorFormula number1, BitvectorFormula number2); /** * Compare the given bitvectors. * * @param number1 a Formula * @param number2 a Formula * @param signed interpret the bitvectors as signed numbers instead of unsigned numbers * @return {@code number1 > number2} */ BooleanFormula greaterThan(BitvectorFormula number1, BitvectorFormula number2, boolean signed); /** * Compare the given bitvectors. * * @param number1 a Formula * @param number2 a Formula * @param signed interpret the bitvectors as signed numbers instead of unsigned numbers * @return {@code number1 >= number2} */ BooleanFormula greaterOrEquals( BitvectorFormula number1, BitvectorFormula number2, boolean signed); /** * Compare the given bitvectors. * * @param number1 a Formula * @param number2 a Formula * @param signed interpret the bitvectors as signed numbers instead of unsigned numbers * @return {@code number1 < number2} */ BooleanFormula lessThan(BitvectorFormula number1, BitvectorFormula number2, boolean signed); /** * Compare the given bitvectors. * * @param number1 a Formula * @param number2 a Formula * @param signed interpret the bitvectors as signed numbers instead of unsigned numbers * @return {@code number1 <= number2} */ BooleanFormula lessOrEquals(BitvectorFormula number1, BitvectorFormula number2, boolean signed); // Bitvector operations /** * This method returns the bit-wise complement of the given bitvector. * * @param bits Formula * @return {@code ~bits} */ BitvectorFormula not(BitvectorFormula bits); /** * This method returns the bit-wise AND of the given bitvectors. * * @param bits1 a Formula * @param bits2 a Formula * @return {@code bits1 & bits2} */ BitvectorFormula and(BitvectorFormula bits1, BitvectorFormula bits2); /** * This method returns the bit-wise OR of the given bitvectors. * * @param bits1 a Formula * @param bits2 a Formula * @return {@code bits1 | bits2} */ BitvectorFormula or(BitvectorFormula bits1, BitvectorFormula bits2); /** * This method returns the bit-wise XOR of the given bitvectors. * * @param bits1 a Formula * @param bits2 a Formula * @return {@code bits1 ^ bits2} */ BitvectorFormula xor(BitvectorFormula bits1, BitvectorFormula bits2); /** * This method returns a term representing the right shift of number by toShift. The result has * the same length as the given number. On the left side, we fill up the most significant bits * with ones (i.e., arithmetic shift), if the number is signed and negative, else we fill up with * zeroes. */ BitvectorFormula shiftRight(BitvectorFormula number, BitvectorFormula toShift, boolean signed); /** * This method returns a term representing the left shift of number by toShift. The result has the * same length as the given number. On the right side, we fill up the least significant bits with * zeroes. */ BitvectorFormula shiftLeft(BitvectorFormula number, BitvectorFormula toShift); /** Concatenate two bitvectors. */ BitvectorFormula concat(BitvectorFormula prefix, BitvectorFormula suffix); /** * Extract a range of bits from a bitvector. We require {@code 0 <= lsb <= msb < bitsize}. * * <p>If msb equals lsb, then a single bit will be returned, i.e., the bit from the given * position. If lsb equals 0 and msb equals bitsize-1, then the complete bitvector will be * returned. * * @param number from where the bits are extracted. * @param msb Upper index for the most significant bit. Must be in interval from lsb to bitsize-1. * @param lsb Lower index for the least significant bit. Must be in interval from 0 to msb. */ BitvectorFormula extract(BitvectorFormula number, int msb, int lsb); /** * Extend a bitvector to the left (add most significant bits). If signed is set and the given * number is negative, then the bit "1" will be added several times, else "0". * * @param number The bitvector to extend. * @param extensionBits How many bits to add. * @param signed Whether the extension should depend on the sign bit. */ BitvectorFormula extend(BitvectorFormula number, int extensionBits, boolean signed); /** All given bitvectors are pairwise unequal. */ BooleanFormula distinct(List<BitvectorFormula> pBits); }
10,828
35.338926
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/BooleanFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** A formula of the boolean sort. */ @Immutable public interface BooleanFormula extends Formula {}
429
25.875
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/BooleanFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.Set; import java.util.stream.Collector; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; /** Manager for dealing with boolean formulas. */ public interface BooleanFormulaManager { /** * Returns a {@link BooleanFormula} representing the given value. * * @param value the boolean value the returned <code>Formula</code> should represent * @return a Formula representing the given value */ default BooleanFormula makeBoolean(boolean value) { return value ? makeTrue() : makeFalse(); } /** Shortcut for {@code makeBoolean(true)}. */ BooleanFormula makeTrue(); /** Shortcut for {@code makeBoolean(false)}. */ BooleanFormula makeFalse(); /** * Creates a variable with exactly the given name. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ BooleanFormula makeVariable(String pVar); /** * Creates a formula representing an equivalence of the two arguments. * * @param formula1 a Formula * @param formula2 a Formula * @return {@code formula1 <-> formula2} */ BooleanFormula equivalence(BooleanFormula formula1, BooleanFormula formula2); /** * @return {@code formula1 => formula2}. */ BooleanFormula implication(BooleanFormula formula1, BooleanFormula formula2); /** * Check, if the formula is the formula "TRUE". This does not include a satisfiability check, but * only a syntactical matching. However, depending on the SMT solver, there might be some * pre-processing of formulas such that trivial cases like "1==1" are recognized and rewritten as * "TRUE", and thus such formulas might also be matched. */ boolean isTrue(BooleanFormula formula); /** * Check, if the formula is the formula "FALSE". This does not include a satisfiability check, but * only a syntactical matching. However, depending on the SMT solver, there might be some * pre-processing of formulas such that trivial cases like "1==2" are recognized and rewritten as * "FALSE", and thus such formulas might also be matched. */ boolean isFalse(BooleanFormula formula); /** * Creates a formula representing {@code IF cond THEN f1 ELSE f2}. * * @param cond a Formula * @param f1 a Formula * @param f2 a Formula * @return (IF cond THEN f1 ELSE f2) */ <T extends Formula> T ifThenElse(BooleanFormula cond, T f1, T f2); /** * Creates a formula representing a negation of the argument. * * @param bits a Formula * @return {@code !bits} */ BooleanFormula not(BooleanFormula bits); /** * Creates a formula representing an AND of the two arguments. * * @param bits1 a Formula * @param bits2 a Formula * @return {@code bits1 & bits2} */ BooleanFormula and(BooleanFormula bits1, BooleanFormula bits2); /** * @see #and(BooleanFormula, BooleanFormula) */ BooleanFormula and(Collection<BooleanFormula> bits); /** * @see #and(BooleanFormula, BooleanFormula) */ BooleanFormula and(BooleanFormula... bits); /** Return a stream {@link Collector} that creates a conjunction of all elements in the stream. */ Collector<BooleanFormula, ?, BooleanFormula> toConjunction(); /** * Creates a formula representing an OR of the two arguments. * * @param bits1 a Formula * @param bits2 a Formula * @return {@code bits1 | bits2} */ BooleanFormula or(BooleanFormula bits1, BooleanFormula bits2); /** * @see #or(BooleanFormula, BooleanFormula) */ BooleanFormula or(Collection<BooleanFormula> bits); /** * @see #or(BooleanFormula, BooleanFormula) */ BooleanFormula or(BooleanFormula... bits); /** Return a stream {@link Collector} that creates a disjunction of all elements in the stream. */ Collector<BooleanFormula, ?, BooleanFormula> toDisjunction(); /** Creates a formula representing XOR of the two arguments. */ BooleanFormula xor(BooleanFormula bits1, BooleanFormula bits2); /** Visit the formula with the given visitor. */ @CanIgnoreReturnValue <R> R visit(BooleanFormula pFormula, BooleanFormulaVisitor<R> visitor); /** * Visit the formula recursively with a given {@link BooleanFormulaVisitor}. * * <p>This method guarantees that the traversal is done iteratively, without using Java recursion, * and thus is not prone to StackOverflowErrors. * * <p>Furthermore, this method also guarantees that every equal part of the formula is visited * only once. Thus, it can be used to traverse DAG-like formulas efficiently. */ void visitRecursively(BooleanFormula f, BooleanFormulaVisitor<TraversalProcess> rFormulaVisitor); /** * Visit the formula recursively with a given {@link BooleanFormulaVisitor}. The arguments each * visitor method receives are <b>already</b> transformed. * * <p>This method guarantees that the traversal is done iteratively, without using Java recursion, * and thus is not prone to StackOverflowErrors. * * <p>Furthermore, this method also guarantees that every equal part of the formula is visited * only once. Thus, it can be used to traverse DAG-like formulas efficiently. */ BooleanFormula transformRecursively( BooleanFormula f, BooleanFormulaTransformationVisitor pVisitor); /** * Return a set of formulas such that a conjunction over them is equivalent to the input formula. * * <p>Example output: * * <ul> * <li>For conjunction {@code A /\ B /\ C}: {@code A, B, C} * <li>For "true": empty set. * <li>For anything else: singleton set consisting of the input formula. * </ul> * * @param flatten If {@code true}, flatten recursively. */ Set<BooleanFormula> toConjunctionArgs(BooleanFormula f, boolean flatten); /** * Return a set of formulas such that a disjunction over them is equivalent to the input formula. * * <p>Example output: * * <ul> * <li>For conjunction {@code A \/ B \/ C}: {@code A, B, C} * <li>For "false": empty set. * <li>For anything else: singleton set consisting of the input formula. * </ul> * * @param flatten If {@code true}, flatten recursively. */ Set<BooleanFormula> toDisjunctionArgs(BooleanFormula f, boolean flatten); }
6,979
33.554455
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/EnumerationFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** A formula of the enumeration sort. */ @Immutable public interface EnumerationFormula extends Formula {}
437
26.375
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/EnumerationFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.sosy_lab.java_smt.api.FormulaType.EnumerationFormulaType; /** * This interface represents the theory of enumeration, i.e., datatype of limited domain sort (as * defined in the SMTLIB2 standard). */ public interface EnumerationFormulaManager { /** * Declare an enumeration. * * @param pName the unique name to identify the new enumeration type. * @param ppElementNames names for all individual elements of this enumeration type. */ EnumerationFormulaType declareEnumeration(String pName, Set<String> ppElementNames); /** * @see #declareEnumeration(String, Set) */ default EnumerationFormulaType declareEnumeration(String pName, String... pElementNames) { final Set<String> elements = ImmutableSet.copyOf(pElementNames); Preconditions.checkArgument( pElementNames.length == elements.size(), "An enumeration type requires pairwise distinct elements. " + "The following elements were given multiple times: %s", FluentIterable.from(pElementNames).filter(e -> !elements.contains(e))); return declareEnumeration(pName, elements); } /** * Creates a constant of given enumeration type with exactly the given name. This constant * (symbol) needs to be an element from the given enumeration type. */ EnumerationFormula makeConstant(String pName, EnumerationFormulaType pType); /** * Creates a variable of given enumeration type with exactly the given name. * * <p>This variable (symbol) represents a "String" for which the SMT solver needs to find a model. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ EnumerationFormula makeVariable(String pVar, EnumerationFormulaType pType); /** * Make a {@link BooleanFormula} that represents the equality of two {@link EnumerationFormula} of * identical enumeration type. */ BooleanFormula equivalence(EnumerationFormula pEnumeration1, EnumerationFormula pEnumeration2); }
2,670
37.710145
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/Evaluator.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.math.BigInteger; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; /** * This class provides methods to get concrete evaluations for formulas from the satisfiable solver * environment. * * <p>This class can be (but does not need to be!) a cheaper and more light-weight version of a * {@link Model} and it misses several features compared to a full {@link Model}: * * <ul> * <li>no listing of model assignments, i.e., the user needs to query each formula on its own, * <li>no guaranteed availability after applying any operation on the original prover stack, i.e., * the evaluation is only available directly after querying the solver with a satisfiable * environment. * </ul> * * <p>If any of these features is required, please use the complete {@link Model}. */ public interface Evaluator extends AutoCloseable { /** * Evaluate a given formula substituting the values from the model and return it as formula. * * <p>If a value is not relevant to the satisfiability result, the solver can choose either to * insert an arbitrary value (e.g., the value <code>0</code> for the matching type) or just return * <code>null</code>. * * <p>The formula does not need to be a variable, we also allow complex expression. The solver * will replace all symbols from the formula with their model values and then simplify the formula * into a simple formula, e.g., consisting only of a numeral expression. * * @param formula Input formula to be evaluated. * @return evaluation of the given formula or <code>null</code> if the solver does not provide a * better evaluation. */ @Nullable <T extends Formula> T eval(T formula); /** * Evaluate a given formula substituting the values from the model. * * <p>If a value is not relevant to the satisfiability result, the model can choose either an * arbitrary value (e.g., the value <code>0</code> for the matching type) or just return <code> * null</code>. * * <p>The formula does not need to be a variable, we also allow complex expression. * * @param formula Input formula * @return Either of: - Number (Rational/Double/BigInteger/Long/Integer) - Boolean * @throws IllegalArgumentException if a formula has unexpected type, e.g. Array. */ @Nullable Object evaluate(Formula formula); /** * Type-safe evaluation for integer formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable BigInteger evaluate(IntegerFormula formula); /** * Type-safe evaluation for rational formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable Rational evaluate(RationalFormula formula); /** * Type-safe evaluation for boolean formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable Boolean evaluate(BooleanFormula formula); /** * Type-safe evaluation for bitvector formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable BigInteger evaluate(BitvectorFormula formula); /** * Type-safe evaluation for string formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable String evaluate(StringFormula formula); /** * Type-safe evaluation for enumeration formulas. * * <p>The formula does not need to be a variable, we also allow complex expression. */ @Nullable String evaluate(EnumerationFormula formula); /** * Free resources associated with this evaluator (existing {@link Formula} instances stay valid, * but {@link #evaluate(Formula)} etc. must not be called again). */ @Override void close(); }
4,275
35.862069
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FloatingPointFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** Formula of the floating point sort. */ @Immutable public interface FloatingPointFormula extends Formula {}
440
26.5625
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FloatingPointFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.math.BigDecimal; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; /** * Floating point operations. * * <p>Most operations are overloaded: there is an option of either using the default rounding mode * (set via the option {@code solver.floatingPointRoundingMode}), or providing the rounding mode * explicitly. */ public interface FloatingPointFormulaManager { FloatingPointFormula makeNumber(double n, FloatingPointType type); FloatingPointFormula makeNumber( double n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula makeNumber(BigDecimal n, FloatingPointType type); FloatingPointFormula makeNumber( BigDecimal n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula makeNumber(String n, FloatingPointType type); FloatingPointFormula makeNumber( String n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula makeNumber(Rational n, FloatingPointType type); FloatingPointFormula makeNumber( Rational n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode); /** * Creates a variable with exactly the given name. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ FloatingPointFormula makeVariable(String pVar, FloatingPointType type); FloatingPointFormula makePlusInfinity(FloatingPointType type); FloatingPointFormula makeMinusInfinity(FloatingPointType type); FloatingPointFormula makeNaN(FloatingPointType type); /** * Build a formula of compatible type from a {@link FloatingPointFormula}. This method uses the * default rounding mode. * * <p>Compatible formula types are all numeral types and (signed/unsigned) bitvector types. It is * also possible to cast a floating-point number into another floating-point type. We do not * support casting from boolean or array types. We try to keep an exact representation, however * fall back to rounding if needed. * * @param source the source formula of floating-point type * @param signed if a {@link BitvectorFormula} is given as target, we additionally use this flag. * Otherwise, we ignore it. * @param targetType the type of the resulting formula * @throws IllegalArgumentException if an incompatible type is used, e.g. a {@link * FloatingPointFormula} cannot be cast to {@link BooleanFormula}. */ <T extends Formula> T castTo( FloatingPointFormula source, boolean signed, FormulaType<T> targetType); /** * Build a formula of compatible type from a {@link FloatingPointFormula}. * * <p>Compatible formula types are all numeral types and (signed/unsigned) bitvector types. It is * also possible to cast a floating-point number into another floating-point type. We do not * support casting from boolean or array types. We try to keep an exact representation, however * fall back to rounding if needed. * * @param source the source formula of floating-point type * @param signed if a {@link BitvectorFormula} is given as target, we additionally use this flag. * Otherwise, we ignore it. * @param targetType the type of the resulting formula * @param pFloatingPointRoundingMode if rounding is needed, we apply the rounding mode. * @throws IllegalArgumentException if an incompatible type is used, e.g. a {@link * FloatingPointFormula} cannot be cast to {@link BooleanFormula}. */ <T extends Formula> T castTo( FloatingPointFormula source, boolean signed, FormulaType<T> targetType, FloatingPointRoundingMode pFloatingPointRoundingMode); /** * Build a {@link FloatingPointFormula} from another compatible formula. This method uses the * default rounding mode. * * <p>Compatible formula types are all numeral types and (signed/unsigned) bitvector types. It is * also possible to cast a floating-point number into another floating-point type. We do not * support casting from boolean or array types. We try to keep an exact representation, however * fall back to rounding if needed. * * @param source the source formula of compatible type * @param signed if a {@link BitvectorFormula} is given as source, we additionally use this flag. * Otherwise, we ignore it. * @param targetType the type of the resulting formula * @throws IllegalArgumentException if an incompatible type is used, e.g. a {@link BooleanFormula} * cannot be cast to {@link FloatingPointFormula}. */ FloatingPointFormula castFrom(Formula source, boolean signed, FloatingPointType targetType); /** * Build a {@link FloatingPointFormula} from another compatible formula. * * <p>Compatible formula types are all numeral types and (signed/unsigned) bitvector types. It is * also possible to cast a floating-point number into another floating-point type. We do not * support casting from boolean or array types. We try to keep an exact representation, however * fall back to rounding if needed. * * @param source the source formula of compatible type * @param signed if a {@link BitvectorFormula} is given as source, we additionally use this flag. * Otherwise, we ignore it. * @param targetType the type of the resulting formula * @param pFloatingPointRoundingMode if rounding is needed, we apply the rounding mode. * @throws IllegalArgumentException if an incompatible type is used, e.g. a {@link BooleanFormula} * cannot be cast to {@link FloatingPointFormula}. */ FloatingPointFormula castFrom( Formula source, boolean signed, FloatingPointType targetType, FloatingPointRoundingMode pFloatingPointRoundingMode); /** * Create a formula that interprets the given bitvector as a floating-point value in the IEEE * format, according to the given type. The sum of the sizes of exponent and mantissa of the * target type plus 1 (for the sign bit) needs to be equal to the size of the bitvector. * * <p>Note: This method will return a value that is (numerically) far away from the original * value. This method is completely different from {@link #castFrom}, which will produce a * floating-point value close to the numeral value. */ FloatingPointFormula fromIeeeBitvector(BitvectorFormula number, FloatingPointType pTargetType); /** * Create a formula that produces a representation of the given floating-point value as a * bitvector conforming to the IEEE format. The size of the resulting bitvector is the sum of the * sizes of the exponent and mantissa of the input formula plus 1 (for the sign bit). */ BitvectorFormula toIeeeBitvector(FloatingPointFormula number); FloatingPointFormula round(FloatingPointFormula formula, FloatingPointRoundingMode roundingMode); // ----------------- Arithmetic relations, return type NumeralFormula ----------------- FloatingPointFormula negate(FloatingPointFormula number); FloatingPointFormula abs(FloatingPointFormula number); FloatingPointFormula max(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula min(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula sqrt(FloatingPointFormula number); FloatingPointFormula sqrt(FloatingPointFormula number, FloatingPointRoundingMode roundingMode); FloatingPointFormula add(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula add( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula subtract(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula subtract( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula divide(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula divide( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode); FloatingPointFormula multiply(FloatingPointFormula number1, FloatingPointFormula number2); FloatingPointFormula multiply( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode); // ----------------- Numeric relations, return type BooleanFormula ----------------- /** * Create a term for assigning one floating-point term to another. This means both terms are * considered equal afterwards. This method is the same as the method <code>equal</code> for other * theories. */ BooleanFormula assignment(FloatingPointFormula number1, FloatingPointFormula number2); /** * Create a term for comparing the equality of two floating-point terms, according to standard * floating-point semantics (i.e., NaN != NaN). Be careful to not use this method when you really * need {@link #assignment(FloatingPointFormula, FloatingPointFormula)}. */ BooleanFormula equalWithFPSemantics(FloatingPointFormula number1, FloatingPointFormula number2); BooleanFormula greaterThan(FloatingPointFormula number1, FloatingPointFormula number2); BooleanFormula greaterOrEquals(FloatingPointFormula number1, FloatingPointFormula number2); BooleanFormula lessThan(FloatingPointFormula number1, FloatingPointFormula number2); BooleanFormula lessOrEquals(FloatingPointFormula number1, FloatingPointFormula number2); BooleanFormula isNaN(FloatingPointFormula number); BooleanFormula isInfinity(FloatingPointFormula number); BooleanFormula isZero(FloatingPointFormula number); BooleanFormula isNormal(FloatingPointFormula number); BooleanFormula isSubnormal(FloatingPointFormula number); /** checks whether a formula is negative, including -0.0. */ BooleanFormula isNegative(FloatingPointFormula number); }
10,622
43.078838
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FloatingPointRoundingMode.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; /** Possible floating point rounding modes. */ public enum FloatingPointRoundingMode { NEAREST_TIES_TO_EVEN, NEAREST_TIES_AWAY, TOWARD_POSITIVE, TOWARD_NEGATIVE, TOWARD_ZERO }
462
23.368421
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FloatingPointRoundingModeFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** * Formula representing a rounding mode for floating-point operations. This is currently unused by * the API but necessary for traversal of formulas with such terms. */ @Immutable public interface FloatingPointRoundingModeFormula extends Formula {}
584
29.789474
98
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/Formula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; /** An arbitrary SMT formula. */ @Immutable public interface Formula { /** * returns an arbitrary representation of the formula, might be human- or machine-readable. * * <p>We do not guarantee that the returned String is in any way related to the formula. The * solver might apply escaping or even un-escaping. A user should not use the returned String for * further processing. For analyzing formulas, we recommend using a {@link FormulaVisitor}. */ @Override String toString(); /** * checks whether the other object is a formula of the same structure. Does not apply an expensive * SAT-check to check equisatisfiability. * * <p>Two formulas that are structured in the same way, are determined as "equal". Due to * transformations and simplifications, two equisatisfiable formulas with different structure * might not be determined as "equal". */ @Override boolean equals(Object other); /** returns a valid hashCode satisfying the constraints given by {@link #equals}. */ @Override int hashCode(); }
1,448
32.697674
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.List; import java.util.Map; import org.sosy_lab.common.Appender; import org.sosy_lab.java_smt.api.visitors.FormulaTransformationVisitor; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; /** FormulaManager class contains all operations which can be performed on formulas. */ public interface FormulaManager { /** * Returns the Integer-Theory. Because most SAT-solvers support automatic casting between Integer- * and Rational-Theory, the Integer- and the RationalFormulaManager both return the same Formulas * for numeric operations like ADD, SUBTRACT, TIMES, LESSTHAN, EQUAL and others. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ IntegerFormulaManager getIntegerFormulaManager(); /** * Returns the Rational-Theory. Because most SAT-solvers support automatic casting between * Integer- and Rational-Theory, the Integer- and the RationalFormulaManager both return the same * Formulas for numeric operations like ADD, SUBTRACT, TIMES, LESSTHAN, EQUAL, etc. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ RationalFormulaManager getRationalFormulaManager(); /** Returns the Boolean-Theory. */ BooleanFormulaManager getBooleanFormulaManager(); /** * Returns the Array-Theory. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ ArrayFormulaManager getArrayFormulaManager(); /** * Returns the Bitvector-Theory. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ BitvectorFormulaManager getBitvectorFormulaManager(); /** * Returns the Floating-Point-Theory. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ FloatingPointFormulaManager getFloatingPointFormulaManager(); /** Returns the function for dealing with uninterpreted functions (UFs). */ UFManager getUFManager(); /** * Returns the Seperation-Logic-Theory. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ SLFormulaManager getSLFormulaManager(); /** * Returns the interface for handling quantifiers. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ QuantifiedFormulaManager getQuantifiedFormulaManager(); /** * Returns the String Theory. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ StringFormulaManager getStringFormulaManager(); /** * Returns the Enumeration Theory, e.g., also known as 'limited domain'. * * @throws UnsupportedOperationException If the theory is not supported by the solver. */ EnumerationFormulaManager getEnumerationFormulaManager(); /** * Create variable of the type equal to {@code formulaType}. * * @param formulaType the type of the variable. * @param name the name of the variable. * @return the created variable. */ <T extends Formula> T makeVariable(FormulaType<T> formulaType, String name); /** * Create a function application to the given list of arguments. * * @param declaration Function declaration * @param args List of arguments * @return Constructed formula */ <T extends Formula> T makeApplication( FunctionDeclaration<T> declaration, List<? extends Formula> args); /** * Create a function application to the given list of arguments. * * @param declaration Function declaration * @param args List of arguments * @return Constructed formula */ <T extends Formula> T makeApplication(FunctionDeclaration<T> declaration, Formula... args); /** Returns the type of the given Formula. */ <T extends Formula> FormulaType<T> getFormulaType(T formula); /** * Parse a boolean formula given as a String in an SMTLIB file format. We expect exactly one * assertion to be contained in the query. * * <p>Example: <code>(declare-fun x () Int)(assert (= 0 x))</code> * * <p>It depends on the used SMT solver whether the given query must be self-contained and include * declarations for all used symbols or not, and also whether the query is allowed to contain * symbols with equal name, but different type/sort than existing symbols. The safest way is to * always declare all used symbols and to avoid conflicting types for them. * * <p>The behavior of the SMT solver is undefined if commands are provided in the SMTLIB-based * String that are different from declarations or an assertion, such as <code>push/pop</code> or * <code>set-info</code>. Most solvers just ignore those commands. * * <p>Variables that are defined, but not used in the assertion, might be ignored by the SMT * solver and they might not be available for later usage. * * @return A single formula from the assertion in the internal representation. * @throws IllegalArgumentException If the string cannot be parsed. */ BooleanFormula parse(String s) throws IllegalArgumentException; /** * Serialize an input formula to an SMT-LIB format. Very useful when passing formulas between * different solvers. * * <p>To get a String, simply call {@link Object#toString()} on the returned object. This method * is lazy and does not create an output string until the returned object is actually used. * * @return SMT-LIB formula serialization. */ Appender dumpFormula(BooleanFormula pT); /** * Apply a tactic which performs formula transformation. The available tactics depend on the used * solver. */ BooleanFormula applyTactic(BooleanFormula input, Tactic tactic) throws InterruptedException; /** * Simplify an input formula, while ensuring equivalence. * * <p>For solvers that do not provide a simplification API, an original formula is returned. * * @param input The input formula * @return Simplified version of the formula */ <T extends Formula> T simplify(T input) throws InterruptedException; /** * Visit the formula with a given visitor. * * <p>This method does <b>not recursively visit</b> sub-components of a formula its own, so the * given {@link FormulaVisitor} needs to call such visitation on its own. * * <p>Please be aware that calling this method might cause extensive stack usage depending on the * nesting of the given formula and the given {@link FormulaVisitor}. Additionally, sub-formulas * that are used several times in the formula might be visited several times. For an efficient * formula traversing, we also provide {@link #visitRecursively(Formula, FormulaVisitor)}. * * @param f formula to be visited * @param rFormulaVisitor an implementation that provides steps for each kind of formula. */ @CanIgnoreReturnValue <R> R visit(Formula f, FormulaVisitor<R> rFormulaVisitor); /** * Visit the formula recursively with a given {@link FormulaVisitor}. This method traverses * sub-components of a formula automatically, depending on the return value of the {@link * TraversalProcess} in the given {@link FormulaVisitor}. * * <p>This method guarantees that the traversal is done iteratively, without using Java recursion, * and thus is not prone to StackOverflowErrors. * * <p>Furthermore, this method also guarantees that every equal part of the formula is visited * only once. Thus, it can be used to traverse DAG-like formulas efficiently. * * <p>The traversal is done in PRE-ORDER manner with regard to caching identical subtrees, i.e., a * parent will be visited BEFORE its children. The unmodified child-formulas are passed as * argument to the parent's visitation. */ void visitRecursively(Formula f, FormulaVisitor<TraversalProcess> rFormulaVisitor); /** * Visit the formula recursively with a given {@link FormulaVisitor}. * * <p>This method guarantees that the traversal is done iteratively, without using Java recursion, * and thus is not prone to StackOverflowErrors. * * <p>Furthermore, this method also guarantees that every equal part of the formula is visited * only once. Thus, it can be used to traverse DAG-like formulas efficiently. * * <p>The traversal is done in POST-ORDER manner with regard to caching identical subtrees, i.e., * a parent will be visited AFTER its children. The result of the child-visitation is passed as * argument to the parent's visitation. * * @param pFormulaVisitor Transformation described by the user. */ <T extends Formula> T transformRecursively(T f, FormulaTransformationVisitor pFormulaVisitor); /** * Extract the names of all free variables and UFs in a formula. * * @param f The input formula * @return Map from variable names to the corresponding formulas. */ ImmutableMap<String, Formula> extractVariables(Formula f); /** * Extract the names of all free variables and UFs in a formula. * * @param f The input formula * @return Map from variable names to the corresponding formulas. If an UF occurs multiple times * in the input formula, an arbitrary instance of an application of this UF is in the map. */ ImmutableMap<String, Formula> extractVariablesAndUFs(Formula f); /** * Substitute every occurrence of any item from {@code changeFrom} in formula {@code f} to the * corresponding occurrence from {@code changeTo}. * * <p>E.g. if {@code changeFrom} contains a variable {@code a} and {@code changeTo} contains a * variable {@code b} all occurrences of {@code a} will be changed to {@code b} in the returned * formula. * * @param f Formula to change. * @param fromToMapping Mapping of old and new formula parts. * @return Formula with parts replaced. */ <T extends Formula> T substitute(T f, Map<? extends Formula, ? extends Formula> fromToMapping); /** * Translates the formula from another context into the context represented by {@code this}. * Default implementation relies on string serialization ({@link #dumpFormula(BooleanFormula)} and * {@link #parse(String)}), but each solver may implement more efficient translation between its * own contexts. * * @param formula Formula belonging to {@code otherContext}. * @param otherManager Formula manager belonging to the other context. * @return Formula belonging to {@code this} context. */ BooleanFormula translateFrom(BooleanFormula formula, FormulaManager otherManager); /** * Check whether the given String can be used as symbol/name for variables or undefined functions. * * <p>We explicitly state that with further development of SMT solvers and the SMTLib * specification, the list of forbidden variable names may change in the future. Users should if * possible not use logical or mathematical operators, or keywords strongly depending on SMTlib. * * <p>If a variable name is rejected, a possibility is escaping, e.g. either substituting the * whole variable name or just every invalid character with an escaped form. We recommend using an * escape sequence based on the token "JAVASMT", because it might be unusual enough to appear when * encoding a user's problem in SMT. Please note that you might also have to handle escaping the * escape sequence. Examples: * * <ul> * <li>the invalid variable name <code>"="</code> (logical operator for equality) can be * replaced with a string <code>"JAVASMT_EQUALS"</code>. * <li>the invalid SMTlib-escaped variable name <code>"|test|"</code> (the solver SMTInterpol * does not allow the pipe symbol <code>"|"</code> in names) can be replaced with <code> * "JAVASMT_PIPEtestJAVASMT_PIPE"</code>. * </ul> */ boolean isValidName(String variableName); /** * Get an escaped symbol/name for variables or undefined functions, if necessary. * * <p>See {@link #isValidName(String)} for further details. */ String escape(String variableName); /** * Unescape the symbol/name for variables or undefined functions, if necessary. * * <p>The result is undefined for Strings that are not properly escaped. * * <p>See {@link #isValidName(String)} for further details. */ String unescape(String variableName); }
12,798
40.287097
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FormulaType.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.Immutable; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; /** * Type of a formula. * * @param <T> Formula class corresponding to the given formula type. */ @SuppressWarnings("checkstyle:constantname") @Immutable public abstract class FormulaType<T extends Formula> { private FormulaType() {} public boolean isArrayType() { return false; } public boolean isBitvectorType() { return false; } public boolean isBooleanType() { return false; } public boolean isFloatingPointType() { return false; } public boolean isFloatingPointRoundingModeType() { return false; } public boolean isNumeralType() { return false; } public boolean isRationalType() { return false; } public boolean isIntegerType() { return false; } public boolean isSLType() { return false; } public boolean isStringType() { return false; } public boolean isRegexType() { return false; } public boolean isEnumerationType() { return false; } @Override public abstract String toString(); /** return the correctly formatted SMTLIB2 type declaration. */ public abstract String toSMTLIBString(); @Immutable public abstract static class NumeralType<T extends NumeralFormula> extends FormulaType<T> { @Override public final boolean isNumeralType() { return true; } } public static final FormulaType<RationalFormula> RationalType = new NumeralType<>() { @Override public boolean isRationalType() { return true; } @Override public String toString() { return "Rational"; } @Override public String toSMTLIBString() { return "Real"; } }; public static final FormulaType<IntegerFormula> IntegerType = new NumeralType<>() { @Override public boolean isIntegerType() { return true; } @Override public String toString() { return "Integer"; } @Override public String toSMTLIBString() { return "Int"; } }; public static final FormulaType<BooleanFormula> BooleanType = new FormulaType<>() { @Override public boolean isBooleanType() { return true; } @Override public String toString() { return "Boolean"; } @Override public String toSMTLIBString() { return "Bool"; } }; public static BitvectorType getBitvectorTypeWithSize(int size) { return new BitvectorType(size); } @Immutable public static final class BitvectorType extends FormulaType<BitvectorFormula> { private final int size; private BitvectorType(int size) { this.size = size; } @Override public boolean isBitvectorType() { return true; } public int getSize() { return size; } @Override public String toString() { return "Bitvector<" + getSize() + ">"; } @Override public boolean equals(Object pObj) { if (pObj == this) { return true; } if (!(pObj instanceof BitvectorType)) { return false; } BitvectorType other = (BitvectorType) pObj; return size == other.size; } @Override public int hashCode() { return size; } @Override public String toSMTLIBString() { return "(_ BitVec " + size + ")"; } } public static FloatingPointType getFloatingPointType(int exponentSize, int mantissaSize) { return new FloatingPointType(exponentSize, mantissaSize); } public static FloatingPointType getSinglePrecisionFloatingPointType() { return FloatingPointType.SINGLE_PRECISION_FP_TYPE; } public static FloatingPointType getDoublePrecisionFloatingPointType() { return FloatingPointType.DOUBLE_PRECISION_FP_TYPE; } @Immutable public static final class FloatingPointType extends FormulaType<FloatingPointFormula> { private static final FloatingPointType SINGLE_PRECISION_FP_TYPE = new FloatingPointType(8, 23); private static final FloatingPointType DOUBLE_PRECISION_FP_TYPE = new FloatingPointType(11, 52); private final int exponentSize; private final int mantissaSize; private FloatingPointType(int pExponentSize, int pMantissaSize) { exponentSize = pExponentSize; mantissaSize = pMantissaSize; } @Override public boolean isFloatingPointType() { return true; } public int getExponentSize() { return exponentSize; } public int getMantissaSize() { return mantissaSize; } /** Return the total size of a value of this type in bits. */ public int getTotalSize() { return exponentSize + mantissaSize + 1; } @Override public int hashCode() { return (31 + exponentSize) * 31 + mantissaSize; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof FloatingPointType)) { return false; } FloatingPointType other = (FloatingPointType) obj; return this.exponentSize == other.exponentSize && this.mantissaSize == other.mantissaSize; } @Override public String toString() { return "FloatingPoint<exp=" + exponentSize + ",mant=" + mantissaSize + ">"; } @Override public String toSMTLIBString() { return "(_ FloatingPoint " + exponentSize + " " + mantissaSize + ")"; } } public static final FormulaType<FloatingPointRoundingModeFormula> FloatingPointRoundingModeType = new FloatingPointRoundingModeType(); private static class FloatingPointRoundingModeType extends FormulaType<FloatingPointRoundingModeFormula> { @Override public boolean isFloatingPointRoundingModeType() { return true; } @Override public String toString() { return "FloatingPointRoundingMode"; } @Override public String toSMTLIBString() { throw new UnsupportedOperationException( "rounding mode is not expected in symbol declarations"); } } @SuppressWarnings("MethodTypeParameterName") public static <TD extends Formula, TR extends Formula> ArrayFormulaType<TD, TR> getArrayType( FormulaType<TD> pDomainSort, FormulaType<TR> pRangeSort) { return new ArrayFormulaType<>(pDomainSort, pRangeSort); } @SuppressWarnings("ClassTypeParameterName") public static final class ArrayFormulaType<TI extends Formula, TE extends Formula> extends FormulaType<ArrayFormula<TI, TE>> { private final FormulaType<TE> elementType; private final FormulaType<TI> indexType; private ArrayFormulaType(FormulaType<TI> pIndexType, FormulaType<TE> pElementType) { this.indexType = Preconditions.checkNotNull(pIndexType); this.elementType = Preconditions.checkNotNull(pElementType); } public FormulaType<TE> getElementType() { return elementType; } public FormulaType<TI> getIndexType() { return indexType; } @Override public boolean isArrayType() { return true; } @Override public String toString() { return String.format("Array<%s,%s>", indexType, elementType); } @Override public int hashCode() { return 31 * elementType.hashCode() + indexType.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ArrayFormulaType)) { return false; } ArrayFormulaType<?, ?> other = (ArrayFormulaType<?, ?>) obj; return elementType.equals(other.elementType) && indexType.equals(other.indexType); } @Override public String toSMTLIBString() { return "(Array " + indexType.toSMTLIBString() + " " + elementType.toSMTLIBString() + ")"; } } public static EnumerationFormulaType getEnumerationType(String pName, Set<String> pElements) { return new EnumerationFormulaType(pName, pElements); } public static final class EnumerationFormulaType extends FormulaType<EnumerationFormula> { private final String name; private final ImmutableSet<String> elements; private EnumerationFormulaType(String pName, Set<String> pElements) { this.name = Preconditions.checkNotNull(pName); this.elements = ImmutableSet.copyOf(pElements); } public String getName() { return name; } public ImmutableSet<String> getElements() { return elements; } public int getCardinality() { return elements.size(); } @Override public boolean isEnumerationType() { return true; } @Override public String toString() { return String.format("%s (%s)", name, Joiner.on(", ").join(elements)); } @Override public int hashCode() { return 31 * name.hashCode() + elements.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof EnumerationFormulaType)) { return false; } EnumerationFormulaType other = (EnumerationFormulaType) obj; return name.equals(other.name) && elements.equals(other.elements); } @Override public String toSMTLIBString() { return "(" + this + ")"; } } public static final FormulaType<StringFormula> StringType = new FormulaType<>() { @Override public boolean isStringType() { return true; } @Override public String toString() { return "String"; } @Override public String toSMTLIBString() { return "String"; } }; public static final FormulaType<RegexFormula> RegexType = new FormulaType<>() { @Override public boolean isRegexType() { return true; } @Override public String toString() { return "RegLan"; } @Override public String toSMTLIBString() { return "RegLan"; } }; /** * Parse a string and return the corresponding type. This method is the counterpart of {@link * #toString()}. */ public static FormulaType<?> fromString(String t) { if (BooleanType.toString().equals(t)) { return BooleanType; } else if (IntegerType.toString().equals(t)) { return IntegerType; } else if (RationalType.toString().equals(t)) { return RationalType; } else if (StringType.toString().equals(t)) { return StringType; } else if (RegexType.toString().equals(t)) { return RegexType; } else if (FloatingPointRoundingModeType.toString().equals(t)) { return FloatingPointRoundingModeType; } else if (t.startsWith("FloatingPoint<")) { // FloatingPoint<exp=11,mant=52> List<String> exman = Splitter.on(',').limit(2).splitToList(t.substring(14, t.length() - 1)); return FormulaType.getFloatingPointType( Integer.parseInt(exman.get(0).substring(4)), Integer.parseInt(exman.get(1).substring(5))); } else if (t.startsWith("Bitvector<")) { // Bitvector<32> return FormulaType.getBitvectorTypeWithSize( Integer.parseInt(t.substring(10, t.length() - 1))); } else if (t.matches(".*\\(.*\\)")) { // Color (Red, Green, Blue) String name = t.substring(0, t.indexOf("(") - 1); String elementsStr = t.substring(t.indexOf("(") + 1, t.length() - 1); Set<String> elements = ImmutableSet.copyOf(Splitter.on(", ").split(elementsStr)); return new EnumerationFormulaType(name, elements); } else { throw new AssertionError("unknown type:" + t); } } }
12,379
24.316973
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FunctionDeclaration.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; /** * Function declaration, for both UFs and built-in functions (theory and boolean). * * <p>Can be instantiated using {@link FormulaManager#makeApplication} */ @Immutable public interface FunctionDeclaration<E extends Formula> { /** * @return Type of the function (LT / GT / UF / etc...). */ FunctionDeclarationKind getKind(); /** * @return Name of the function (UF name / "LT" / etc...). */ String getName(); /** * @return Sort of the function output. */ FormulaType<E> getType(); /** * @return Sorts of the arguments. */ ImmutableList<FormulaType<?>> getArgumentTypes(); }
1,001
22.857143
82
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/FunctionDeclarationKind.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; /** * Types of function declarations. * * @see FunctionDeclaration */ public enum FunctionDeclarationKind { AND, NOT, OR, /** If and only if. */ IFF, /** If-then-else operator. */ ITE, /** Exclusive OR over two formulas. */ XOR, /** Implication between two boolean formulas. */ IMPLIES, /** Distinct operator for a set of numeric formulas. */ DISTINCT, /** Store and select on arrays. */ STORE, SELECT, // Simple arithmetic, // they work across integers and rationals. /** Unary minus. */ UMINUS, /** Subtraction over integers and rationals. */ SUB, /** Addition over integers and rationals. */ ADD, /** Division over rationals and integer division over integers. */ DIV, /** Multiplication over integers and rationals. */ MUL, /** Modulo operator over integers. */ MODULO, /** Uninterpreted function. */ UF, /** User-defined variable. */ VAR, /** Less-than over integers and rationals. */ LT, /** Less-than-or-equal over integers and rationals. */ LTE, /** Greater-than over integers and rationals. */ GT, /** Greater-than-or-equal over integers and rationals. */ GTE, /** Equality over integers and rationals. Binary equality is modelled with {@code IFF}. */ EQ, /** Unary comparison to zero. */ EQ_ZERO, /** Unary comparison with zero. */ GTE_ZERO, /** Floor operation, converts from rationals to integers, also known as {@code to_int}. */ FLOOR, /** Identity operation, converts from integers to rationals, also known as {@code to_real}. */ TO_REAL, // Simple bitvector operations /** Extraction over bitvectors. */ BV_EXTRACT, /** Concatenation over bitvectors. */ BV_CONCAT, /** Extend bitvectors according to their sign. */ BV_SIGN_EXTENSION, /** Extend bitvectors with zeros. */ BV_ZERO_EXTENSION, /** Bitwise negation of a bitvector. */ BV_NOT, /** Negation of a bitvector. */ BV_NEG, /** Bitwise OR over bitvectors. */ BV_OR, /** Bitwise AND over bitvectors. */ BV_AND, /** Bitwise XOR over bitvectors. */ BV_XOR, /** Subtraction over bitvectors. */ BV_SUB, /** Addition over bitvectors. */ BV_ADD, /** Signed division over bitvectors. */ BV_SDIV, /** Unsigned division over bitvectors. */ BV_UDIV, /** Signed remainder over bitvectors. */ BV_SREM, /** Unsigned remainder over bitvectors. */ BV_UREM, /** Multiplication over bitvectors. */ BV_MUL, /** Signed less-than over bitvectors. */ BV_ULT, /** Unsigned less-than over bitvectors. */ BV_SLT, /** Unsigned less-than-or-equal over bitvectors. */ BV_ULE, /** Signed greater-than-or-equal over bitvectors. */ BV_SLE, /** Signed greater-than over bitvectors. */ BV_UGT, /** Unsigned greater-than over bitvectors. */ BV_SGT, /** Unsigned greater-than-or-equal over bitvectors. */ BV_UGE, /** Signed greater-than-or-equal over bitvectors. */ BV_SGE, /** Equality over bitvectors. Binary equality is modeled with {@code IFF}. */ BV_EQ, /** Logical left-shift over bitvectors (fill from right with zeroes). */ BV_SHL, /** Logical right-shift over bitvectors (fill from left with zeroes). */ BV_LSHR, /** Arithmetic right-shift over bitvectors (fill from left with value of first bit). */ BV_ASHR, /** Cast an unsigned bitvector to a floating-point number. */ BV_UCASTTO_FP, /** Cast a signed bitvector to a floating-point number. */ BV_SCASTTO_FP, // Simple floating point operations /** Negation of a floating point. */ FP_NEG, /** Absolute value of a floating point. */ FP_ABS, /** Maximum of two floating points. */ FP_MAX, /** Minimum of two floating points. */ FP_MIN, /** Square root of a floating point. */ FP_SQRT, /** Subtraction over floating points. */ FP_SUB, /** Addition over floating points. */ FP_ADD, /** Division over floating points. */ FP_DIV, /** Multiplication over floating points. */ FP_MUL, /** Less-than over floating points. */ FP_LT, /** Less-than-or-equal over floating points. */ FP_LE, /** Greater-than-or-equal over floating points. */ FP_GE, /** Greater-than over floating points. */ FP_GT, /** Equal over floating points. */ FP_EQ, /** Rounding over floating points. */ FP_ROUND_EVEN, /** Rounding over floating points. */ FP_ROUND_AWAY, /** Rounding over floating points. */ FP_ROUND_POSITIVE, /** Rounding over floating points. */ FP_ROUND_NEGATIVE, /** Rounding over floating points. */ FP_ROUND_ZERO, /** Rounding over floating points. */ FP_ROUND_TO_INTEGRAL, /** Further FP queries. */ FP_IS_NAN, FP_IS_INF, FP_IS_ZERO, FP_IS_NEGATIVE, FP_IS_SUBNORMAL, FP_IS_NORMAL, FP_CASTTO_FP, FP_CASTTO_SBV, FP_CASTTO_UBV, FP_AS_IEEEBV, FP_FROM_IEEEBV, // String and Regex theory STR_CONCAT, STR_PREFIX, STR_SUFFIX, STR_CONTAINS, STR_SUBSTRING, STR_REPLACE, STR_REPLACE_ALL, STR_CHAR_AT, STR_LENGTH, STR_INDEX_OF, STR_TO_RE, STR_IN_RE, STR_TO_INT, INT_TO_STR, STR_LT, STR_LE, RE_PLUS, RE_STAR, RE_OPTIONAL, RE_CONCAT, RE_UNION, RE_RANGE, RE_INTERSECT, RE_COMPLEMENT, RE_DIFFERENCE, // default case /** * Solvers support a lot of different built-in theories. We enforce standardization only across a * small subset. */ OTHER }
5,672
18.036913
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/IntegerFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.math.BigInteger; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; /** * Interface which operates over {@link IntegerFormula}s. * * <p>Integer formulas always take integral formulas as arguments. */ public interface IntegerFormulaManager extends NumeralFormulaManager<IntegerFormula, IntegerFormula> { /** Create a term representing the constraint {@code number1 == number2 (mod n)}. */ BooleanFormula modularCongruence(IntegerFormula number1, IntegerFormula number2, BigInteger n); /** Create a term representing the constraint {@code number1 == number2 (mod n)}. */ BooleanFormula modularCongruence(IntegerFormula number1, IntegerFormula number2, long n); /** * Create a formula representing the modulo of two operands. * * <p>If the denumerator evaluates to zero (modulo-by-zero), either directly as value or * indirectly via an additional constraint, then the solver is allowed to choose an arbitrary * value for the result of the modulo operation (cf. SMTLIB standard for the division operator in * Ints or Reals theory). * * <p>Note: Some solvers, e.g., Yices2, abort with an exception when exploring a modulo-by-zero * during the SAT-check. This is not compliant to the SMTLIB standard, but sadly happens. */ IntegerFormula modulo(IntegerFormula numerator, IntegerFormula denumerator); @Override default FormulaType<IntegerFormula> getFormulaType() { return FormulaType.IntegerType; } }
1,761
37.304348
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/InterpolatingProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; /** * This class provides an interface to an incremental SMT solver with methods for pushing and * popping formulas as well as SAT checks. Furthermore, interpolants can be generated for an * unsatisfiable list of formulas. * * @see ProverEnvironment The non-interpolating ProverEnvironment for general notes that also apply * to this interface. * @param <T> The type of the objects which can be used to select formulas for interpolant creation. */ public interface InterpolatingProverEnvironment<T> extends BasicProverEnvironment<T> { /** * Get an interpolant for two groups of formulas. This should be called only immediately after an * {@link #isUnsat()} call that returned <code>true</code>. * * <p>There is no direct guarantee that the interpolants returned are part of an inductive * sequence', however this seems to work for most (all?) solvers as long as the same proof is * used, i.e. all interpolants are computed after the same SAT-check. * * @param formulasOfA A collection of values returned by {@link #push(BooleanFormula)}. All the * corresponding formulas from group A, the remaining formulas form group B. * @return An interpolant for A and B * @throws SolverException if interpolant cannot be computed, for example because interpolation * procedure is incomplete */ BooleanFormula getInterpolant(Collection<T> formulasOfA) throws SolverException, InterruptedException; /** * This method returns interpolants of an 'inductive sequence'. This property must be supported by * the interpolation-strategy of the underlying SMT-solver! Depending on the underlying SMT-solver * this method might be faster than N direct calls to getInterpolant(). * * <p>The prover stack should contain the partitioned formulas, but any order is allowed. For an * input of N partitions we return N-1 interpolants. Any asserted formula that is on the prover * stack and not part of the partitioned list, will be used for background theory and its symbols * can appear in any interpolant. * * @return a 'inductive sequence' of interpolants, such that the implication {@code AND(I_i, P_i) * => I_(i+1)} is satisfied for all i, where P_i is the conjunction of all formulas in * partition i. * @throws SolverException if interpolant cannot be computed, for example because interpolation * procedure is incomplete */ default List<BooleanFormula> getSeqInterpolants(List<? extends Collection<T>> partitionedFormulas) throws SolverException, InterruptedException { // a 'tree' with all subtrees starting at 0 is called a 'sequence' return getTreeInterpolants(partitionedFormulas, new int[partitionedFormulas.size()]); } /** * This utility method wraps each formula in a collection and then forwards to {@link * #getSeqInterpolants}. * * @see #getSeqInterpolants */ default List<BooleanFormula> getSeqInterpolants0(List<T> formulas) throws SolverException, InterruptedException { return getSeqInterpolants(Lists.transform(formulas, ImmutableSet::of)); } /** * Compute a sequence of interpolants. The nesting array describes the start of the subtree for * tree interpolants. For inductive sequences of interpolants use a nesting array completely * filled with 0. * * <p>Example: * * <pre> * A D * | | * B E * | / * C * | * F H * | / * G * * arrayIndex = [0,1,2,3,4,5,6,7] // only for demonstration, not needed * partition = [A,B,D,E,C,F,H,G] // post-order of tree * startOfSubTree = [0,0,2,2,0,0,6,0] // index of left-most leaf of the current element * </pre> * * <p>The prover stack should contain the partitioned formulas. For an input of N partitions * (nodes in the tree) we return N-1 interpolants (one interpolant for/below each node except the * root). Any asserted formula that is on the prover stack and not part of the partitioned list, * will be used for background theory and its symbols can appear in any interpolant. * * @param partitionedFormulas of formulas * @param startOfSubTree The start of the subtree containing the formula at this index as root. * @return Tree interpolants respecting the nesting relation. * @throws SolverException if interpolant cannot be computed, for example because interpolation * procedure is incomplete */ List<BooleanFormula> getTreeInterpolants( List<? extends Collection<T>> partitionedFormulas, int[] startOfSubTree) throws SolverException, InterruptedException; /** * This utility method wraps each formula in a collection and then forwards to {@link * #getTreeInterpolants}. * * @see #getTreeInterpolants */ default List<BooleanFormula> getTreeInterpolants0(List<T> formulas, int[] startOfSubTree) throws SolverException, InterruptedException { return getTreeInterpolants(Lists.transform(formulas, ImmutableSet::of), startOfSubTree); } /** Checks for a valid subtree-structure. This code is taken from SMTinterpol. */ static boolean checkTreeStructure(int numOfPartitions, int[] startOfSubTree) { Preconditions.checkArgument(numOfPartitions > 0, "at least one partition should be available."); Preconditions.checkArgument( numOfPartitions == startOfSubTree.length, "partitions and subtree table must have equal length."); for (int i = 0; i < numOfPartitions; i++) { Preconditions.checkArgument(startOfSubTree[i] >= 0, "tree contains negative node."); int j = i; while (startOfSubTree[i] < j) { j = startOfSubTree[j - 1]; } Preconditions.checkArgument(startOfSubTree[i] == j, "invalid leaf of tree."); } Preconditions.checkArgument(startOfSubTree[numOfPartitions - 1] == 0, "invalid root of tree."); return true; } }
6,348
42.486301
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/Model.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.Iterator; import java.util.List; import java.util.Objects; import org.sosy_lab.java_smt.api.Model.ValueAssignment; /** * This class provides a model with concrete evaluations for symbols and formulas from the * satisfiable solver environment. * * <p>This class is an extensions of {@link Evaluator} and provides more features: * * <ul> * <li>a listing of model assignments, i.e., the user can iterate over all available symbols and * their assignments, * <li>a guaranteed availability even after applying any operation on the original prover stack, i * .e., the model instance stays constant and remains valid for one given satisfiable prover * environment. * </ul> */ public interface Model extends Evaluator, Iterable<ValueAssignment>, AutoCloseable { /** * Iterate over all values present in the model. Note that iterating multiple times may be * inefficient for some solvers, it is recommended to use {@link * BasicProverEnvironment#getModelAssignments()} instead in this case. * * <p>The iteration includes value assignments for... * * <ul> * <li>all relevant free variables of simple type. If a variable is irrelevant for * satisfiability, it can be <code>null</code> or missing in the iteration. * <li>(nested) arrays with all accesses. If an array access is applied within a quantified * context, some value assignments can be missing in the iteration. Please use a direct * evaluation query to get the evaluation in such a case. * <li>uninterpreted functions with all applications. If an uninterpreted function is applied * within a quantified context, some value assignments can be missing in the iteration. * Please use a direct evaluation query to get the evaluation in such a case. * </ul> */ @Override default Iterator<ValueAssignment> iterator() { return asList().iterator(); } /** Build a list of assignments that stays valid after closing the model. */ ImmutableList<ValueAssignment> asList(); /** * Pretty-printing of the model values. * * <p>Please only use this method for debugging and not for retrieving relevant information about * the model. The returned model representation is not intended for further usage like parsing, * because we do not guarantee any specific format, e.g., for arrays and uninterpreted functions, * and we allow the SMT solver to include arbitrary additional information about the current * solver state, e.g., any available symbol in the solver, even from other provers, and temporary * internal symbols. */ @Override String toString(); /** * Free resources associated with this model (existing {@link ValueAssignment} instances stay * valid, but {@link #evaluate(Formula)} etc. and {@link #iterator()} must not be called again). */ @Override void close(); final class ValueAssignment { /** * the key should be of simple formula-type (Boolean/Integer/Rational/BitVector). * * <p>For UFs we use the application of the UF with arguments. * * <p>For arrays we use the selection-statement with an index. We do not support Array theory as * {@link #value} during a model evaluation, but we provide assignments like <code> * select(arr, 12) := 34</code> where <code>arr</code> itself is a plain symbol (without an * explicit const- or zero-based initialization, as done by some SMT solvers). */ private final Formula keyFormula; /** the value should be of simple formula-type (Boolean/Integer/Rational/BitVector). */ private final Formula valueFormula; /** the equality of key and value. */ private final BooleanFormula formula; /** the key should be boolean or numeral (Rational/Double/BigInteger/Long/Integer). */ private final Object value; /** * arguments can have any type. We would prefer numerals (like value), but we also allow * Formulas. * * <p>For UFs we use the arguments. * * <p>For arrays we use the index of a selection or an empty list for wildcard-selection, if the * whole array is filled with a constant value. In the latter case any additionally given * array-assignment overrides the wildcard-selection for the given index. Example: "arr=0, * arr[2]=3" corresponds to an array {0,0,3,0,...}. */ private final ImmutableList<Object> argumentsInterpretation; /** * The name should be a 'useful' identifier for the current assignment. * * <p>For UFs we use their name without parameters. Parameters are given as {@link * #argumentsInterpretation}. * * <p>For arrays we use the name without any index. The index is given as {@link * #argumentsInterpretation}, if required. */ private final String name; public ValueAssignment( Formula keyFormula, Formula valueFormula, BooleanFormula formula, String name, Object value, List<?> argumentInterpretation) { this.keyFormula = Preconditions.checkNotNull(keyFormula); this.valueFormula = Preconditions.checkNotNull(valueFormula); this.formula = Preconditions.checkNotNull(formula); this.name = Preconditions.checkNotNull(name); this.value = Preconditions.checkNotNull(value); this.argumentsInterpretation = ImmutableList.copyOf(argumentInterpretation); } /** The formula AST which is assigned a given value. */ public Formula getKey() { return keyFormula; } /** The formula AST which is assigned to a given key. */ public Formula getValueAsFormula() { return valueFormula; } /** The formula AST representing the equality of key and value. */ public BooleanFormula getAssignmentAsFormula() { return formula; } /** Variable name for variables, function name for UFs, and array name for arrays. */ public String getName() { return name; } /** * Value: see the {@link #evaluate} methods for the possible types. * * <p>We return only values that can be used in Java, i.e., boolean or numeral values * (Rational/Double/BigInteger/Long/Integer). */ public Object getValue() { return value; } /** Interpretation assigned for function arguments. Empty for variables. */ public ImmutableList<Object> getArgumentsInterpretation() { return argumentsInterpretation; } public boolean isFunction() { return !argumentsInterpretation.isEmpty(); } public int getArity() { return argumentsInterpretation.size(); } public Object getArgInterpretation(int i) { assert i < getArity(); return argumentsInterpretation.get(i); } @Override public String toString() { StringBuilder sb = new StringBuilder().append(name); if (!argumentsInterpretation.isEmpty()) { sb.append('('); Joiner.on(", ").appendTo(sb, argumentsInterpretation); sb.append(')'); } return sb.append(": ").append(value).toString(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof ValueAssignment)) { return false; } ValueAssignment other = (ValueAssignment) o; // "Key" is purposefully not included in the comparison, // name and arguments should be sufficient. return name.equals(other.name) && value.equals(other.value) && argumentsInterpretation.equals(other.argumentsInterpretation); } @Override public int hashCode() { return Objects.hash(name, argumentsInterpretation, value); } } }
8,153
35.079646
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/NumeralFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** Formulas of any numeral sort. */ @Immutable public interface NumeralFormula extends Formula { @Immutable interface IntegerFormula extends NumeralFormula {} @Immutable interface RationalFormula extends NumeralFormula {} }
564
23.565217
69
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/NumeralFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; /** * This interface represents the Numeral Theory. * * @param <ParamFormulaType> formulaType of the parameters * @param <ResultFormulaType> formulaType of arithmetic results */ public interface NumeralFormulaManager< ParamFormulaType extends NumeralFormula, ResultFormulaType extends NumeralFormula> { ResultFormulaType makeNumber(long number); ResultFormulaType makeNumber(BigInteger number); /** * Create a numeric literal with a given value. Note: if the theory represented by this instance * cannot handle rational numbers, the value may get rounded or otherwise represented imprecisely. */ ResultFormulaType makeNumber(double number); /** * Create a numeric literal with a given value. Note: if the theory represented by this instance * cannot handle rational numbers, the value may get rounded or otherwise represented imprecisely. */ ResultFormulaType makeNumber(BigDecimal number); ResultFormulaType makeNumber(String pI); ResultFormulaType makeNumber(Rational pRational); /** * Creates a variable with exactly the given name. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ ResultFormulaType makeVariable(String pVar); FormulaType<ResultFormulaType> getFormulaType(); // ----------------- Arithmetic relations, return type NumeralFormula ----------------- ResultFormulaType negate(ParamFormulaType number); ResultFormulaType add(ParamFormulaType number1, ParamFormulaType number2); ResultFormulaType sum(List<ParamFormulaType> operands); ResultFormulaType subtract(ParamFormulaType number1, ParamFormulaType number2); /** * Create a formula representing the division of two operands. * * <p>If the denumerator evaluates to zero (division-by-zero), either directly as value or * indirectly via an additional constraint, then the solver is allowed to choose an arbitrary * value for the result of the division (cf. SMTLIB standard for the division operator in Ints or * Reals theory). * * <p>Note: Some solvers, e.g., Yices2, abort with an exception when exploring a division-by-zero * during the SAT-check. This is not compliant to the SMTLIB standard, but sadly happens. */ ResultFormulaType divide(ParamFormulaType numerator, ParamFormulaType denumerator); ResultFormulaType multiply(ParamFormulaType number1, ParamFormulaType number2); // ----------------- Numeric relations, return type BooleanFormula ----------------- BooleanFormula equal(ParamFormulaType number1, ParamFormulaType number2); /** All given numbers are pairwise unequal. */ BooleanFormula distinct(List<ParamFormulaType> pNumbers); BooleanFormula greaterThan(ParamFormulaType number1, ParamFormulaType number2); BooleanFormula greaterOrEquals(ParamFormulaType number1, ParamFormulaType number2); BooleanFormula lessThan(ParamFormulaType number1, ParamFormulaType number2); BooleanFormula lessOrEquals(ParamFormulaType number1, ParamFormulaType number2); /** * The {@code floor} operation returns the nearest integer formula that is less or equal to the * given argument formula. * * <p>For rational formulas, SMTlib2 denotes this operation as {@code to_int}. */ IntegerFormula floor(ParamFormulaType formula); }
4,007
36.457944
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/OptimizationProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.util.Optional; import org.sosy_lab.common.rationals.Rational; /** Interface for optimization modulo SMT. */ public interface OptimizationProverEnvironment extends BasicProverEnvironment<Void>, AutoCloseable { /** * Add the maximization <code>objective</code>. * * <p><b>Note: {@code push/pop} may be used for switching objectives</b> * * @return Objective handle, to be used for retrieving the value. */ int maximize(Formula objective); /** * Add minimization <code>objective</code>. * * <p><b>Note: {@code push/pop} may be used for switching objectives</b> * * @return Objective handle, to be used for retrieving the value. */ int minimize(Formula objective); /** * Optimize the objective function subject to the previously imposed constraints. * * @return Status of the optimization problem. */ OptStatus check() throws InterruptedException, SolverException; /** * @param epsilon Value to substitute for the {@code epsilon}. * @return Upper approximation of the optimized value, or absent optional if the objective is * unbounded. */ Optional<Rational> upper(int handle, Rational epsilon); /** * @param epsilon Value to substitute for the {@code epsilon}. * @return Lower approximation of the optimized value, or absent optional if the objective is * unbounded. */ Optional<Rational> lower(int handle, Rational epsilon); /** * {@inheritDoc} * * <p>Please note that the prover is allowed to use standard numbers for any real variable in the * model after a sat-query returned {@link OptStatus#OPT}. For integer formulas, we expect the * optimal assignment. * * <p>Example 1: For the constraint 'x&lt;10' with a real x, the upper bound of x is '10-epsilon' * (epsilon can even be set to zero). The model can return the assignment x=9. To get an optimal * assignment, query the solver with an additional constraint 'x == 10-epsilon'. * * <p>Example 2: For the constraint 'x&lt;10' with an integer x, the upper bound of x is '9' * (epsilon is irrelevant here and can be zero). The model returns the optimal assignment x=9. */ @Override Model getModel() throws SolverException; /** Status of the optimization problem. */ enum OptStatus { /** The solution was found (may be unbounded). */ OPT, /** The set of constraints is unsatisfiable. */ UNSAT, /** The result is unknown. */ UNDEF } }
2,759
31.093023
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/PackageSanityTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.testing.AbstractPackageSanityTests; public class PackageSanityTest extends AbstractPackageSanityTests { { setDistinctValues(FormulaType.class, FormulaType.BooleanType, FormulaType.IntegerType); } }
509
25.842105
91
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/ProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import org.sosy_lab.common.ShutdownNotifier; /** * An interface to an incremental SMT solver with methods for pushing and popping formulas as well * as SAT checks. Instances of this class can be used once for a series of related queries. After * that, the {@link #close} method should be called (preferably using the try-with-resources * syntax). All methods are expected to throw {@link IllegalStateException}s after close was called. * * <p>All solving methods are expected to throw {@link SolverException} if the solver fails to solve * the given query, and {@link InterruptedException} if a thread interrupt was requested or a * shutdown request via the {@link ShutdownNotifier}. It is not guaranteed, though, that solvers * respond in a timely manner (or at all) to shut down or interrupt requests. */ public interface ProverEnvironment extends BasicProverEnvironment<Void> {}
1,169
45.8
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/QuantifiedFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableList; import java.util.List; /** * This interface contains methods for working with any theory with quantifiers. * * <p>ATTENTION: Not every theory has a quantifier elimination property! */ public interface QuantifiedFormulaManager { enum Quantifier { FORALL, EXISTS } /** * @return An existentially quantified formula. * @param pVariables The variables that will get bound (variables) by the quantification. * @param pBody The {@link BooleanFormula}} within that the binding will be performed. * @throws IllegalArgumentException If the list {@code pVariables} is empty. */ default BooleanFormula exists(List<? extends Formula> pVariables, BooleanFormula pBody) { return mkQuantifier(Quantifier.EXISTS, pVariables, pBody); } /** * @return A universally quantified formula. * @param pVariables The variables that will get bound (variables) by the quantification. * @param pBody The {@link BooleanFormula}} within that the binding will be performed. * @throws IllegalArgumentException If the list {@code pVariables} is empty. */ default BooleanFormula forall(List<? extends Formula> pVariables, BooleanFormula pBody) { return mkQuantifier(Quantifier.FORALL, pVariables, pBody); } /** Syntax sugar, see {@link #forall(List, BooleanFormula)}. */ default BooleanFormula forall(Formula quantifiedArg, BooleanFormula pBody) { return forall(ImmutableList.of(quantifiedArg), pBody); } /** Syntax sugar, see {@link #exists(List, BooleanFormula)}. */ default BooleanFormula exists(Formula quantifiedArg, BooleanFormula pBody) { return exists(ImmutableList.of(quantifiedArg), pBody); } /** * @return A quantified formula * @param q Quantifier type * @param pVariables The variables that will get bound (variables) by the quantification. * @param pBody The {@link BooleanFormula}} within that the binding will be performed. * @throws IllegalArgumentException If the list {@code pVariables} is empty. */ BooleanFormula mkQuantifier( Quantifier q, List<? extends Formula> pVariables, BooleanFormula pBody); /** * Eliminate the quantifiers for a given formula. If this is not possible, it will return the * input formula. Note that CVC4 only supports this for LIA and LRA. * * @param pF Formula with quantifiers. * @return New formula without quantifiers. */ BooleanFormula eliminateQuantifiers(BooleanFormula pF) throws InterruptedException, SolverException; }
2,814
36.039474
95
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/RationalFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; /** * Interface for operating over {@link RationalFormula}. * * <p>Rational formulas may take both integral and rational formulas as arguments. */ public interface RationalFormulaManager extends NumeralFormulaManager<NumeralFormula, RationalFormula> { @Override default FormulaType<RationalFormula> getFormulaType() { return FormulaType.RationalType; } }
716
26.576923
82
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/RegexFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Alejandro Serrano Mena // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** A formula of the string sort. */ @Immutable public interface RegexFormula extends Formula {}
411
24.75
54
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/SLFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; /** * The {@link SLFormulaManager} can build formulae for separation logic. * * <p>Info: A {@link ProverEnvironment} only supports the assertion of well-typed SL-formulae, i.e. * all formulae for one heap need to use matching types (sorts) for the AdressFormulae and * ValueFormulae. The user has to take care of this, otherwise the {@link ProverEnvironment} * complains at runtime! */ @SuppressWarnings("MethodTypeParameterName") public interface SLFormulaManager { BooleanFormula makeStar(BooleanFormula f1, BooleanFormula f2); <AF extends Formula, VF extends Formula> BooleanFormula makePointsTo(AF ptr, VF to); BooleanFormula makeMagicWand(BooleanFormula f1, BooleanFormula f2); <AF extends Formula, VF extends Formula, AT extends FormulaType<AF>, VT extends FormulaType<VF>> BooleanFormula makeEmptyHeap(AT pAdressType, VT pValueType); <AF extends Formula, AT extends FormulaType<AF>> AF makeNilElement(AT pAdressType); }
1,231
36.333333
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/SolverContext.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.collect.ImmutableMap; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; /** * Instances of this interface provide access to an SMT solver. A single SolverContext should be * used only from a single thread. * * <p>If you wish to use multiple contexts (even for the same solver), create one SolverContext per * each. Formulas can be transferred between different contexts using {@link * FormulaManager#translateFrom(BooleanFormula, FormulaManager)}. */ public interface SolverContext extends AutoCloseable { /** Get the formula manager, which is used for formula manipulation. */ FormulaManager getFormulaManager(); /** Options for the prover environment. */ enum ProverOptions { /** * Whether the solver should generate models (i.e., satisfying assignments) for satisfiable * formulas. */ GENERATE_MODELS, /** * Whether the solver should allow to query all satisfying assignments for satisfiable formulas. */ GENERATE_ALL_SAT, /** * Whether the solver should generate an unsat core for unsatisfiable formulas. Unsat core is * generated over all formulas asserted with {@link * ProverEnvironment#addConstraint(BooleanFormula)} or {@link * ProverEnvironment#push(BooleanFormula)}. */ GENERATE_UNSAT_CORE, /** * Whether the solver should generate an unsat core for unsatisfiable formulas <b>only</b> over * the assumptions explicitly passed to the solver. */ GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS, /** Whether the solver should enable support for formulae build in SL theory. */ ENABLE_SEPARATION_LOGIC } /** * Create a fresh new {@link ProverEnvironment} which encapsulates an assertion stack and can be * used to check formulas for unsatisfiability. * * @param options Options specified for the prover environment. All the options specified in * {@link ProverOptions} are turned off by default. */ ProverEnvironment newProverEnvironment(ProverOptions... options); /** * Create a fresh new {@link InterpolatingProverEnvironment} which encapsulates an assertion stack * and allows generating and retrieve interpolants for unsatisfiable formulas. If the SMT solver * is able to handle satisfiability tests with assumptions please consider implementing the {@link * InterpolatingProverEnvironment} interface, and return an Object of this type here. * * @param options Options specified for the prover environment. All the options specified in * {@link ProverOptions} are turned off by default. */ InterpolatingProverEnvironment<?> newProverEnvironmentWithInterpolation(ProverOptions... options); /** * Create a fresh new {@link OptimizationProverEnvironment} which encapsulates an assertion stack * and allows solving optimization queries. * * @param options Options specified for the prover environment. All the options specified in * {@link ProverOptions} are turned off by default. */ OptimizationProverEnvironment newOptimizationProverEnvironment(ProverOptions... options); /** * Get version information out of the solver. * * <p>In most cases, the version contains the name of the solver followed by some numbers and * additional info about the version, e.g., "SMTInterpol 2.5-12-g3d15a15c". */ String getVersion(); /** * Get solver name (MATHSAT5/Z3/etc...). * * <p>This is an uppercase String matching the enum identifier from {@link Solvers} */ Solvers getSolverName(); /** * Get statistics for a complete solver context. The returned mapping is intended to provide the * solver-internal statistics. The keys can differ between individual solvers. * * <p>Calling the statistics several times for the same context returns accumulated number, i.e., * we currently do not provide any possibility to reset the statistics. * * <p>We do not guarantee any specific key to be present, as this depends on the used solver. We * might even return an empty mapping if the solver does not support calling this method or is in * an invalid state. * * @see ProverEnvironment#getStatistics() */ default ImmutableMap<String, String> getStatistics() { return ImmutableMap.of(); } /** * Close the solver context. * * <p>After calling this method, further access to any object that had been returned from this * context is not wanted, i.e., it depends on the solver. Java-based solvers might wait for the * next garbage collection with any cleanup operation. Native solvers might even reference invalid * memory and cause segmentation faults. * * <p>Necessary for the solvers implemented in native code, frees the associated memory. */ @Override void close(); }
5,088
37.263158
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/SolverException.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import org.checkerframework.checker.nullness.qual.Nullable; /** Exception thrown if there is an error during SMT solving. */ public class SolverException extends Exception { private static final long serialVersionUID = -1557936144555925180L; public SolverException(@Nullable String msg) { super(msg); } public SolverException(@Nullable String msg, @Nullable Throwable t) { super(msg, t); } }
690
25.576923
71
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/StringFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Alejandro Serrano Mena // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.errorprone.annotations.Immutable; /** A formula of the string sort. */ @Immutable public interface StringFormula extends Formula {}
412
24.8125
54
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/StringFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Alejandro Serrano Mena // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import com.google.common.base.Preconditions; import java.util.Arrays; import java.util.List; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; /** * Manager for dealing with string formulas. Functions come from * http://smtlib.cs.uiowa.edu/theories-UnicodeStrings.shtml. */ public interface StringFormulaManager { /** * Returns a {@link StringFormula} representing the given constant. * * @param value the string value the returned <code>Formula</code> should represent * @return a Formula representing the given value */ StringFormula makeString(String value); /** * Creates a variable of type String with exactly the given name. * * <p>This variable (symbol) represents a "String" for which the SMT solver needs to find a model. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ StringFormula makeVariable(String pVar); // TODO: There is currently no way to use variables of type "Regex", i.e., that represent full // regular expression for which the SMT solver need to find a model. // The reason for this is that the current SMT solvers do not support this feature. // However, we can build a RegexFormula from basic parts like Strings (including // variables of type String) and operations like range, union, or complement. BooleanFormula equal(StringFormula str1, StringFormula str2); BooleanFormula greaterThan(StringFormula str1, StringFormula str2); BooleanFormula greaterOrEquals(StringFormula str1, StringFormula str2); BooleanFormula lessThan(StringFormula str1, StringFormula str2); BooleanFormula lessOrEquals(StringFormula str1, StringFormula str2); /** Check whether the given prefix is a real prefix of str. */ BooleanFormula prefix(StringFormula prefix, StringFormula str); /** Check whether the given suffix is a real suffix of str. */ BooleanFormula suffix(StringFormula suffix, StringFormula str); BooleanFormula contains(StringFormula str, StringFormula part); /** * Get the first index for a substring in a String, or -1 if the substring is not found. * startIndex (inlcuded) denotes the start of the search for the index. */ IntegerFormula indexOf(StringFormula str, StringFormula part, IntegerFormula startIndex); /** * Get a substring of length 1 from the given String. * * <p>The result is underspecified, if the index is out of bounds for the given String. */ StringFormula charAt(StringFormula str, IntegerFormula index); /** * Get a substring from the given String. * * <p>The result is underspecified, if the start index is out of bounds for the given String or if * the requested length is negative. The length of the result is the minimum of the requested * length and the remaining length of the given String. */ StringFormula substring(StringFormula str, IntegerFormula index, IntegerFormula length); /** Replace the first appearances of target in fullStr with the replacement. */ StringFormula replace(StringFormula fullStr, StringFormula target, StringFormula replacement); /** Replace all appearances of target in fullStr with the replacement. */ StringFormula replaceAll(StringFormula fullStr, StringFormula target, StringFormula replacement); IntegerFormula length(StringFormula str); default StringFormula concat(StringFormula... parts) { return concat(Arrays.asList(parts)); } StringFormula concat(List<StringFormula> parts); /** * @param str formula representing the string to match * @param regex formula representing the regular expression * @return a formula representing the acceptance of the string by the regular expression */ BooleanFormula in(StringFormula str, RegexFormula regex); /** * Returns a {@link RegexFormula} representing the given constant. * * <p>This method does not parse an existing regex from String, but uses the String directly as a * constant. * * @param value the regular expression the returned <code>Formula</code> should represent */ RegexFormula makeRegex(String value); // basic regex operations /** * @return formula denoting the empty set of strings */ RegexFormula none(); /** * Note: The size of the used alphabet depends on the underlying SMT solver. * * @return formula denoting the set of all strings, also known as Regex <code>".*"</code>. */ RegexFormula all(); /** * Note: The size of the used alphabet depends on the underlying SMT solver. * * @return formula denoting the set of all strings of length 1, also known as DOT operator which * represents one arbitrary char, or as Regex <code>"."</code>. */ RegexFormula allChar(); /** * @return formula denoting the range regular expression over two sequences of length 1. */ RegexFormula range(StringFormula start, StringFormula end); /** * @return formula denoting the range regular expression over two chars. * @see #range(StringFormula, StringFormula) */ default RegexFormula range(char start, char end) { Preconditions.checkArgument( start <= end, "Range from start '%s' (%s) to end '%s' (%s) is empty.", start, (int) start, end, (int) end); return range(makeString(String.valueOf(start)), makeString(String.valueOf(end))); } /** * @return formula denoting the concatenation */ default RegexFormula concat(RegexFormula... parts) { return concatRegex(Arrays.asList(parts)); } /** * @return formula denoting the concatenation */ // TODO the naming of this function collides with #concat(List<StringFormula>). // Maybe we should split String and Regex manager. RegexFormula concatRegex(List<RegexFormula> parts); /** * @return formula denoting the union */ RegexFormula union(RegexFormula regex1, RegexFormula regex2); /** * @return formula denoting the intersection */ RegexFormula intersection(RegexFormula regex1, RegexFormula regex2); /** * @return formula denoting the Kleene closure */ RegexFormula complement(RegexFormula regex); /** * @return formula denoting the Kleene closure (0 or more), also known as STAR operand. */ RegexFormula closure(RegexFormula regex); // derived regex operations /** * @return formula denoting the difference */ RegexFormula difference(RegexFormula regex1, RegexFormula regex2); /** * @return formula denoting the Kleene cross (1 or more), also known as PLUS operand. */ RegexFormula cross(RegexFormula regex); /** * @return formula denoting the optionality, also known as QUESTIONMARK operand. */ RegexFormula optional(RegexFormula regex); /** * @return formula denoting the concatenation n times */ RegexFormula times(RegexFormula regex, int repetitions); /** * Interpret a String formula as an Integer formula. * * <p>The number is interpreted in base 10 and has no leading zeros. The method works as expected * for positive numbers, including zero. It returns the constant value of <code>-1</code> for * negative numbers or invalid number representations, for example if any char is no digit. */ IntegerFormula toIntegerFormula(StringFormula str); /** * Interpret an Integer formula as a String formula. * * <p>The number is in base 10. The method works as expected for positive numbers, including zero. * It returns the empty string <code>""</code> for negative numbers. */ StringFormula toStringFormula(IntegerFormula number); }
8,101
33.476596
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/Tactic.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; /** * Tactic is a generic formula to formula transformation. * * <p>Depending on whether the chosen solver supports the transformation, at runtime switches * between solver-provided implementation and our own generic visitor-based one. * * <p>Tactics can be applied using {@link org.sosy_lab.java_smt.api.FormulaManager#applyTactic} */ public enum Tactic { /** * Replaces all applications of UFs with fresh variables and adds constraints to enforce the * functional consistency. Quantified formulas are not supported. */ ACKERMANNIZATION, /** Convert the formula to NNF (negated normal form). */ NNF, /** * Convert the formula to CNF (conjunctive normal form), using extra fresh variables to avoid the * size explosion. The resulting formula is not <i>equivalent</i> but only <i>equisatisfiable</i> * to the original one. * * <p>NB: currently this tactic does not have a default implementation. */ TSEITIN_CNF, /** * Perform "best-effort" quantifier elimination: when the bound variable can be "cheaply" * eliminated using a pattern-matching approach, eliminate it, and otherwise leave it as-is. */ QE_LIGHT, }
1,450
31.244444
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/UFManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api; import java.util.List; /** Manager for dealing with uninterpreted functions (UFs). */ public interface UFManager { /** Declare an uninterpreted function. */ <T extends Formula> FunctionDeclaration<T> declareUF( String name, FormulaType<T> returnType, List<FormulaType<?>> args); /** Declare an uninterpreted function. */ <T extends Formula> FunctionDeclaration<T> declareUF( String name, FormulaType<T> returnType, FormulaType<?>... args); /** * Create an uninterpreted function call. * * <p>Simply delegates to {@link FormulaManager#makeApplication(FunctionDeclaration, List)} * * @param funcType Declaration of the function to call. * @param args Arguments of the function. * @return Instantiated function call. */ <T extends Formula> T callUF(FunctionDeclaration<T> funcType, List<? extends Formula> args); /** * @see #callUF(FunctionDeclaration, List) */ <T extends Formula> T callUF(FunctionDeclaration<T> funcType, Formula... args); /** * Declares and calls an uninterpreted function with exactly the given name. * * <p>Please make sure that the given name is valid in SMT-LIB2. Take a look at {@link * FormulaManager#isValidName} for further information. * * <p>This method does not quote or unquote the given name, but uses the plain name "AS IS". * {@link Formula#toString} can return a different String than the given one. */ <T extends Formula> T declareAndCallUF( String name, FormulaType<T> pReturnType, List<Formula> pArgs); /** * @see #declareAndCallUF(String, FormulaType, List) */ <T extends Formula> T declareAndCallUF(String name, FormulaType<T> pReturnType, Formula... pArgs); }
1,984
33.824561
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** * The core interfaces for abstracting from SMT solvers and providing a common API for all solvers. */ @com.google.errorprone.annotations.CheckReturnValue @javax.annotation.ParametersAreNonnullByDefault @org.sosy_lab.common.annotations.FieldsAreNonnullByDefault @org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault package org.sosy_lab.java_smt.api;
607
34.764706
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/BooleanFormulaTransformationVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; /** * Base class for visitors for boolean formulas that recursively transform boolean formulas. * * @see BooleanFormulaManager#transformRecursively */ public abstract class BooleanFormulaTransformationVisitor implements BooleanFormulaVisitor<BooleanFormula> { private final FormulaManager mgr; private final BooleanFormulaManager bfmgr; protected BooleanFormulaTransformationVisitor(FormulaManager pMgr) { mgr = pMgr; bfmgr = mgr.getBooleanFormulaManager(); } @Override public BooleanFormula visitConstant(boolean value) { return bfmgr.makeBoolean(value); } @Override public BooleanFormula visitBoundVar(BooleanFormula var, int deBruijnIdx) { return var; } @Override public BooleanFormula visitAtom(BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) { return pAtom; } @Override public BooleanFormula visitNot(BooleanFormula processedOperand) { return bfmgr.not(processedOperand); } @Override public BooleanFormula visitAnd(List<BooleanFormula> processedOperands) { return bfmgr.and(processedOperands); } @Override public BooleanFormula visitOr(List<BooleanFormula> processedOperands) { return bfmgr.or(processedOperands); } @Override public BooleanFormula visitXor( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.xor(processedOperand1, processedOperand2); } @Override public BooleanFormula visitEquivalence( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.equivalence(processedOperand1, processedOperand2); } @Override public BooleanFormula visitImplication( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.implication(processedOperand1, processedOperand2); } @Override public BooleanFormula visitIfThenElse( BooleanFormula processedCondition, BooleanFormula processedThenFormula, BooleanFormula processedElseFormula) { return bfmgr.ifThenElse(processedCondition, processedThenFormula, processedElseFormula); } @Override public BooleanFormula visitQuantifier( Quantifier quantifier, BooleanFormula quantifiedAST, List<Formula> boundVars, BooleanFormula processedBody) { return mgr.getQuantifiedFormulaManager().mkQuantifier(quantifier, boundVars, processedBody); } }
3,022
29.23
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/BooleanFormulaVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; /** * Visitor iterating through the boolean part of the formula. Use {@link * BooleanFormulaManager#visit} for visiting formulas. * * @param <R> Desired return type. */ public interface BooleanFormulaVisitor<R> { /** * Visit a constant with a given value. * * @see BooleanFormulaManager#makeBoolean */ R visitConstant(boolean value); /** Visit a boolean variable bound by a quantifier. */ R visitBoundVar(BooleanFormula var, int deBruijnIdx); /** * Visit a NOT-expression. * * @param operand Negated term. * @see BooleanFormulaManager#not */ R visitNot(BooleanFormula operand); /** * Visit an AND-expression with an arbitrary number of boolean arguments. * * <p>An AND-expression with zero arguments is equisatisfiable to 'TRUE'. An AND-expression with * one argument is equal to the argument itself. In all other cases, default boolean logic * applies. * * @see BooleanFormulaManager#and */ R visitAnd(List<BooleanFormula> operands); /** * Visit an OR-expression with an arbitrary number of boolean arguments. * * <p>An OR-expression with zero arguments is equisatisfiable to 'TRUE'. An OR-expression with one * argument is equal to the argument itself. In all other cases, default boolean logic applies. * * @see BooleanFormulaManager#or */ R visitOr(List<BooleanFormula> operands); /** * Visit a XOR-expression. * * @see BooleanFormulaManager#xor */ R visitXor(BooleanFormula operand1, BooleanFormula operand2); /** * Visit an equivalence between two formulas of boolean sort: {@code operand1 = operand2}. * * @see BooleanFormulaManager#equivalence */ R visitEquivalence(BooleanFormula operand1, BooleanFormula operand2); /** * Visit an implication. * * @see BooleanFormulaManager#implication */ R visitImplication(BooleanFormula operand1, BooleanFormula operand2); /** * Visit an if-then-else expression. * * @see BooleanFormulaManager#ifThenElse */ R visitIfThenElse( BooleanFormula condition, BooleanFormula thenFormula, BooleanFormula elseFormula); /** * Visit a quantifier: forall- or exists-. * * @param quantifier Quantifier type: FORALL- or EXISTS- * @param quantifiedAST AST of the quantified node. Provided because it is difficult to re-create * from the parameters. * @param boundVars Variables bound by this quantifier. * @param body Body of the quantified expression. * @see QuantifiedFormulaManager#mkQuantifier * @see QuantifiedFormulaManager#forall * @see QuantifiedFormulaManager#exists */ R visitQuantifier( Quantifier quantifier, BooleanFormula quantifiedAST, List<Formula> boundVars, BooleanFormula body); /** * Visit an SMT atom. An atom can be a theory expression, constant, or a variable. * * <p>This is anything with a boolean sort which is not covered by the cases above. */ R visitAtom(BooleanFormula atom, FunctionDeclaration<BooleanFormula> funcDecl); }
3,683
29.7
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/DefaultBooleanFormulaVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; /** * A formula visitor which allows for the default implementation. * * @param <R> Return type for each traversal operation. */ public abstract class DefaultBooleanFormulaVisitor<R> implements BooleanFormulaVisitor<R> { protected abstract R visitDefault(); @Override public R visitConstant(boolean value) { return visitDefault(); } @Override public R visitBoundVar(BooleanFormula var, int deBruijnIdx) { return visitDefault(); } @Override public R visitAtom(BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) { return visitDefault(); } @Override public R visitNot(BooleanFormula pOperand) { return visitDefault(); } @Override public R visitAnd(List<BooleanFormula> pOperands) { return visitDefault(); } @Override public R visitOr(List<BooleanFormula> pOperands) { return visitDefault(); } @Override public R visitXor(BooleanFormula operand1, BooleanFormula operand2) { return visitDefault(); } @Override public R visitEquivalence(BooleanFormula pOperand1, BooleanFormula pOperand2) { return visitDefault(); } @Override public R visitImplication(BooleanFormula pOperand1, BooleanFormula pOperand2) { return visitDefault(); } @Override public R visitIfThenElse( BooleanFormula pCondition, BooleanFormula pThenFormula, BooleanFormula pElseFormula) { return visitDefault(); } @Override public R visitQuantifier( Quantifier quantifier, BooleanFormula quantifiedAST, List<Formula> boundVars, BooleanFormula body) { return visitDefault(); } }
2,132
23.802326
92
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/DefaultFormulaVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; public abstract class DefaultFormulaVisitor<R> implements FormulaVisitor<R> { /** * Method for default case, is called by all methods from this class if they are not overridden. * * @param f Formula for the currently visited node. * @return An arbitrary value, will be passed through to the caller. */ protected abstract R visitDefault(Formula f); @Override public R visitFreeVariable(Formula f, String name) { return visitDefault(f); } @Override public R visitBoundVariable(Formula f, int deBruijnIdx) { return visitDefault(f); } @Override public R visitConstant(Formula f, Object value) { return visitDefault(f); } @Override public R visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { return visitDefault(f); } @Override public R visitQuantifier( BooleanFormula f, Quantifier q, List<Formula> boundVariables, BooleanFormula body) { return visitDefault(f); } }
1,514
27.055556
98
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/ExpectedFormulaVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import org.sosy_lab.java_smt.api.Formula; /** * Like {@link DefaultFormulaVisitor}, but throws {@link UnsupportedOperationException} on * unexpected formula types. */ public abstract class ExpectedFormulaVisitor<R> extends DefaultFormulaVisitor<R> { @Override protected final R visitDefault(Formula f) { throw new UnsupportedOperationException(); } }
651
26.166667
90
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/FormulaTransformationVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; /** * Abstract class for formula transformation. * * @see org.sosy_lab.java_smt.api.FormulaManager#transformRecursively */ public abstract class FormulaTransformationVisitor implements FormulaVisitor<Formula> { private final FormulaManager fmgr; protected FormulaTransformationVisitor(FormulaManager fmgr) { this.fmgr = fmgr; } @Override public Formula visitFreeVariable(Formula f, String name) { return f; } @Override public Formula visitBoundVariable(Formula f, int deBruijnIdx) { return f; } @Override public Formula visitConstant(Formula f, Object value) { return f; } /** * @param f Input function. * @param newArgs New arguments <b>after</b> the transformation * @param functionDeclaration Function declaration * @return Transformed function. */ @Override public Formula visitFunction( Formula f, List<Formula> newArgs, FunctionDeclaration<?> functionDeclaration) { return fmgr.makeApplication(functionDeclaration, newArgs); } /** * @param f Quantifier formula. * @param quantifier Quantifier type: either {@code FORALL} or {@code EXISTS}. * @param boundVariables Variables bound by the quantifier. <b>NOTE:</b> not all solvers hold * metadata about bound variables. In case this is not available, this method will be called * with an empty list, yet {@code #mkQuantifier} will work fine with an empty list as well. * @param transformedBody Quantifier body <b>already transformed</b> by the visitor. * @return Transformed AST */ @Override public BooleanFormula visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula transformedBody) { return fmgr.getQuantifiedFormulaManager() .mkQuantifier(quantifier, boundVariables, transformedBody); } }
2,428
30.545455
98
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/FormulaVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; /** * Visitor iterating through entire formula. Use {@link FormulaManager#visit} for visiting formulas. * * @param <R> Desired return type. */ public interface FormulaVisitor<R> { /** * Visit a free variable (such as "x", "y" or "z"), not bound by a quantifier. The variable can * have any sort (both boolean and non-boolean). * * @param f Formula representing the variable. * @param name Variable name. */ R visitFreeVariable(Formula f, String name); /** * Visit a variable bound by a quantifier. The variable can have any sort (both boolean and * non-boolean). * * @param f Formula representing the variable. * @param deBruijnIdx de-Bruijn index of the bound variable, which can be used to find the * matching quantifier. */ R visitBoundVariable(Formula f, int deBruijnIdx); /** * Visit a constant, such as "true"/"false", a numeric constant like "1" or "1.0", a String * constant like 2hello world" or enumeration constant like "Blue". * * @param f Formula representing the constant. * @param value The value of the constant. It is either of type {@link Boolean}, of a subtype of * {@link Number} (mostly a {@link BigInteger}, a {@link BigDecimal}, or a {@link Rational}), * or {@link String}. * @return An arbitrary return value that is passed to the caller. */ R visitConstant(Formula f, Object value); /** * Visit an arbitrary, potentially uninterpreted function. The function can have any sort. * * @param f Input function. * @param args List of arguments * @param functionDeclaration Function declaration. Can be given to {@link * FormulaManager#makeApplication} to construct a new instance of the same function with * different arguments. */ R visitFunction(Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration); /** * Visit a quantified node. * * @param f Quantifier formula. * @param quantifier Quantifier type: either {@code FORALL} or {@code EXISTS}. * @param boundVariables Variables bound by the quantifier. <b>NOTE:</b> not all solvers hold * metadata about bound variables. In case this is not available, this method will be called * with an empty list, yet {@code #mkQuantifier} will work fine with an empty list as well. * @param body Body of the quantifier. */ R visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula body); }
3,174
37.253012
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/TraversalProcess.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.api.visitors; import com.google.common.collect.ImmutableSet; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; /** * Return class that lets the visitor guide the recursive formula traversal process started with * {@link FormulaManager#visitRecursively}. or {@link BooleanFormulaManager#visitRecursively}. */ public final class TraversalProcess { /** Continue traversal and recurse into current formula subtree. */ public static final TraversalProcess CONTINUE = new TraversalProcess(TraversalType.CONTINUE_TYPE, ImmutableSet.of()); /** Continue traversal, but do not recurse into current formula subtree. */ public static final TraversalProcess SKIP = new TraversalProcess(TraversalType.SKIP_TYPE, ImmutableSet.of()); /** Immediately abort traversal and return to caller. */ public static final TraversalProcess ABORT = new TraversalProcess(TraversalType.ABORT_TYPE, ImmutableSet.of()); /** * Traverse only the given children. * * <p>NOTE: given formulas which are <em>not</em> children of the given node will be ignored. */ public static TraversalProcess custom(Iterable<? extends Formula> pToTraverse) { return new TraversalProcess(TraversalType.CUSTOM_TYPE, ImmutableSet.copyOf(pToTraverse)); } /** * Traverse only the given child. * * <p>NOTE: any given which is <em>not</em> child of the given node will be ignored. */ public static TraversalProcess custom(Formula pToTraverse) { return new TraversalProcess(TraversalType.CUSTOM_TYPE, ImmutableSet.of(pToTraverse)); } public enum TraversalType { CONTINUE_TYPE, SKIP_TYPE, ABORT_TYPE, CUSTOM_TYPE } private final TraversalType type; private final ImmutableSet<? extends Formula> toTraverse; private TraversalProcess(TraversalType pType, ImmutableSet<? extends Formula> pToTraverse) { type = pType; toTraverse = pToTraverse; } public TraversalType getType() { return type; } public boolean contains(Formula f) { if (type == TraversalType.CONTINUE_TYPE) { return true; } else if (type == TraversalType.SKIP_TYPE || type == TraversalType.ABORT_TYPE) { return false; } else { assert type == TraversalType.CUSTOM_TYPE; return toTraverse.contains(f); } } }
2,648
31.703704
96
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/api/visitors/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** * The visitors of this package allow for efficient traversal, manipulation and transformation of * formulas. */ package org.sosy_lab.java_smt.api.visitors;
403
27.857143
97
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractArrayFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.ArrayFormulaManager; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; @SuppressWarnings({"ClassTypeParameterName", "MethodTypeParameterName"}) public abstract class AbstractArrayFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements ArrayFormulaManager { protected AbstractArrayFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pFormulaCreator) { super(pFormulaCreator); } @SuppressWarnings("unchecked") @Override public <TI extends Formula, TE extends Formula> TE select( ArrayFormula<TI, TE> pArray, TI pIndex) { final FormulaType<? extends Formula> elementType = getFormulaCreator().getArrayFormulaElementType(pArray); // Examples: // Array<Bitvector,Bitvector> // Rational final TFormulaInfo term = select(extractInfo(pArray), extractInfo(pIndex)); return (TE) getFormulaCreator().encapsulate(elementType, term); } protected abstract TFormulaInfo select(TFormulaInfo pArray, TFormulaInfo pIndex); @Override public <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> store( ArrayFormula<TI, TE> pArray, TI pIndex, TE pValue) { final FormulaType<TI> indexType = getFormulaCreator().getArrayFormulaIndexType(pArray); final FormulaType<TE> elementType = getFormulaCreator().getArrayFormulaElementType(pArray); final TFormulaInfo term = store(extractInfo(pArray), extractInfo(pIndex), extractInfo(pValue)); return getFormulaCreator().encapsulateArray(term, indexType, elementType); } protected abstract TFormulaInfo store( TFormulaInfo pArray, TFormulaInfo pIndex, TFormulaInfo pValue); @Override public <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> makeArray( String pName, ArrayFormulaType<TI, TE> type) { return makeArray(pName, type.getIndexType(), type.getElementType()); } @Override public < TI extends Formula, TE extends Formula, FTI extends FormulaType<TI>, FTE extends FormulaType<TE>> ArrayFormula<TI, TE> makeArray(String pName, FTI pIndexType, FTE pElementType) { checkVariableName(pName); final TFormulaInfo namedArrayFormula = internalMakeArray(pName, pIndexType, pElementType); return getFormulaCreator().encapsulateArray(namedArrayFormula, pIndexType, pElementType); } protected abstract <TI extends Formula, TE extends Formula> TFormulaInfo internalMakeArray( String pName, FormulaType<TI> pIndexType, FormulaType<TE> pElementType); @Override public <TI extends Formula> FormulaType<TI> getIndexType(ArrayFormula<TI, ?> pArray) { return getFormulaCreator().getArrayFormulaIndexType(pArray); } @Override public <TE extends Formula> FormulaType<TE> getElementType(ArrayFormula<?, TE> pArray) { return getFormulaCreator().getArrayFormulaElementType(pArray); } @Override public <TI extends Formula, TE extends Formula> BooleanFormula equivalence( ArrayFormula<TI, TE> pArray1, ArrayFormula<TI, TE> pArray2) { return getFormulaCreator() .encapsulateBoolean(equivalence(extractInfo(pArray1), extractInfo(pArray2))); } protected abstract TFormulaInfo equivalence(TFormulaInfo pArray1, TFormulaInfo pArray2); }
3,913
37.372549
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractBaseFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; /** * A BaseFormulaManager because all Abstract*FormulaManager-Classes wrap a FormulaCreator-instance. * * @param <TFormulaInfo> the solver specific type. */ @SuppressWarnings("ClassTypeParameterName") abstract class AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> { protected final FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> formulaCreator; AbstractBaseFormulaManager(FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pFormulaCreator) { this.formulaCreator = pFormulaCreator; } protected final FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> getFormulaCreator() { return formulaCreator; } final TFormulaInfo extractInfo(Formula pBits) { return getFormulaCreator().extractInfo(pBits); } final BooleanFormula wrapBool(TFormulaInfo pTerm) { return getFormulaCreator().encapsulateBoolean(pTerm); } protected final TType toSolverType(FormulaType<?> formulaType) { TType t; if (formulaType.isBooleanType()) { t = getFormulaCreator().getBoolType(); } else if (formulaType.isIntegerType()) { t = getFormulaCreator().getIntegerType(); } else if (formulaType.isRationalType()) { t = getFormulaCreator().getRationalType(); } else if (formulaType.isStringType()) { t = getFormulaCreator().getStringType(); } else if (formulaType.isBitvectorType()) { FormulaType.BitvectorType bitPreciseType = (FormulaType.BitvectorType) formulaType; t = getFormulaCreator().getBitvectorType(bitPreciseType.getSize()); } else if (formulaType.isFloatingPointType()) { FormulaType.FloatingPointType fpType = (FormulaType.FloatingPointType) formulaType; t = getFormulaCreator().getFloatingPointType(fpType); } else if (formulaType.isArrayType()) { FormulaType.ArrayFormulaType<?, ?> arrType = (FormulaType.ArrayFormulaType<?, ?>) formulaType; TType indexType = toSolverType(arrType.getIndexType()); TType elementType = toSolverType(arrType.getElementType()); t = getFormulaCreator().getArrayType(indexType, elementType); } else { throw new IllegalArgumentException("Not supported interface"); } return t; } }
2,603
37.294118
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractBitvectorFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkArgument; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BitvectorFormulaManager; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.BitvectorType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractBitvectorFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements BitvectorFormulaManager { private final AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> bmgr; protected AbstractBitvectorFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator, AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> pBmgr) { super(pCreator); bmgr = pBmgr; } private BitvectorFormula wrap(TFormulaInfo pTerm) { return getFormulaCreator().encapsulateBitvector(pTerm); } private void checkSameSize( BitvectorFormula pNumber1, BitvectorFormula pNumber2, String operation) { final int len1 = getLength(pNumber1); final int len2 = getLength(pNumber2); checkArgument( len1 == len2, "Can't %s bitvectors with different sizes (%s and %s)", operation, len1, len2); } @Override public BitvectorFormula makeBitvector(int length, IntegerFormula pI) { TFormulaInfo param1 = extractInfo(pI); return wrap(makeBitvectorImpl(length, param1)); } protected abstract TFormulaInfo makeBitvectorImpl(int length, TFormulaInfo pParam1); @Override public IntegerFormula toIntegerFormula(BitvectorFormula pI, boolean signed) { TFormulaInfo param1 = extractInfo(pI); return getFormulaCreator() .encapsulate(FormulaType.IntegerType, toIntegerFormulaImpl(param1, signed)); } protected abstract TFormulaInfo toIntegerFormulaImpl(TFormulaInfo pI, boolean signed); @Override public BitvectorFormula negate(BitvectorFormula pNumber) { TFormulaInfo param1 = extractInfo(pNumber); return wrap(negate(param1)); } protected abstract TFormulaInfo negate(TFormulaInfo pParam1); @Override public BitvectorFormula add(BitvectorFormula pNumber1, BitvectorFormula pNumber2) { checkSameSize(pNumber1, pNumber2, "add"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(add(param1, param2)); } protected abstract TFormulaInfo add(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BitvectorFormula subtract(BitvectorFormula pNumber1, BitvectorFormula pNumber2) { checkSameSize(pNumber1, pNumber2, "subtract"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(subtract(param1, param2)); } protected abstract TFormulaInfo subtract(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BitvectorFormula divide( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "divide"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(divide(param1, param2, signed)); } protected abstract TFormulaInfo divide( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BitvectorFormula modulo( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "modulo"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(modulo(param1, param2, signed)); } protected abstract TFormulaInfo modulo( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BitvectorFormula multiply(BitvectorFormula pNumber1, BitvectorFormula pNumber2) { checkSameSize(pNumber1, pNumber2, "modulo"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(multiply(param1, param2)); } protected abstract TFormulaInfo multiply(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula equal(BitvectorFormula pNumber1, BitvectorFormula pNumber2) { checkSameSize(pNumber1, pNumber2, "compare"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(equal(param1, param2)); } protected abstract TFormulaInfo equal(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterThan( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "compare"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterThan(param1, param2, signed)); } protected abstract TFormulaInfo greaterThan( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BooleanFormula greaterOrEquals( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "compare"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterOrEquals(param1, param2, signed)); } protected abstract TFormulaInfo greaterOrEquals( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BooleanFormula lessThan( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "compare"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessThan(param1, param2, signed)); } protected abstract TFormulaInfo lessThan( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BooleanFormula lessOrEquals( BitvectorFormula pNumber1, BitvectorFormula pNumber2, boolean signed) { checkSameSize(pNumber1, pNumber2, "compare"); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessOrEquals(param1, param2, signed)); } protected abstract TFormulaInfo lessOrEquals( TFormulaInfo pParam1, TFormulaInfo pParam2, boolean signed); @Override public BitvectorFormula not(BitvectorFormula pBits) { TFormulaInfo param1 = extractInfo(pBits); return wrap(not(param1)); } protected abstract TFormulaInfo not(TFormulaInfo pParam1); @Override public BitvectorFormula and(BitvectorFormula pBits1, BitvectorFormula pBits2) { checkSameSize(pBits1, pBits2, "combine"); TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(and(param1, param2)); } protected abstract TFormulaInfo and(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BitvectorFormula or(BitvectorFormula pBits1, BitvectorFormula pBits2) { checkSameSize(pBits1, pBits2, "combine"); TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(or(param1, param2)); } protected abstract TFormulaInfo or(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BitvectorFormula xor(BitvectorFormula pBits1, BitvectorFormula pBits2) { checkSameSize(pBits1, pBits2, "combine"); TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(xor(param1, param2)); } protected abstract TFormulaInfo xor(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BitvectorFormula makeBitvector(int pLength, long i) { return wrap(makeBitvectorImpl(pLength, i)); } protected TFormulaInfo makeBitvectorImpl(int pLength, long pI) { return makeBitvectorImpl(pLength, BigInteger.valueOf(pI)); } @Override public BitvectorFormula makeBitvector(int pLength, BigInteger i) { return wrap(makeBitvectorImpl(pLength, i)); } protected abstract TFormulaInfo makeBitvectorImpl(int pLength, BigInteger pI); /** * transform a negative value into its positive counterpart. * * @throws IllegalArgumentException if the value is out of range for the given size. */ protected final BigInteger transformValueToRange(int pLength, BigInteger pI) { final BigInteger max = BigInteger.valueOf(2).pow(pLength); if (pI.signum() < 0) { BigInteger min = BigInteger.valueOf(2).pow(pLength - 1).negate(); Preconditions.checkArgument( pI.compareTo(min) >= 0, "%s is to small for a bitvector with length %s", pI, pLength); pI = pI.add(max); } else { Preconditions.checkArgument( pI.compareTo(max) < 0, "%s is to large for a bitvector with length %s", pI, pLength); } return pI; } @Override public BitvectorFormula makeVariable(BitvectorType type, String pVar) { return makeVariable(type.getSize(), pVar); } @Override public BitvectorFormula makeVariable(int pLength, String pVar) { checkVariableName(pVar); return wrap(makeVariableImpl(pLength, pVar)); } protected abstract TFormulaInfo makeVariableImpl(int pLength, String pVar); /** * Return a term representing the (arithmetic if signed is true) right shift of number by toShift. */ @Override public BitvectorFormula shiftRight( BitvectorFormula pNumber, BitvectorFormula toShift, boolean signed) { TFormulaInfo param1 = extractInfo(pNumber); TFormulaInfo param2 = extractInfo(toShift); return wrap(shiftRight(param1, param2, signed)); } protected abstract TFormulaInfo shiftRight( TFormulaInfo pNumber, TFormulaInfo toShift, boolean signed); @Override public BitvectorFormula shiftLeft(BitvectorFormula pNumber, BitvectorFormula toShift) { TFormulaInfo param1 = extractInfo(pNumber); TFormulaInfo param2 = extractInfo(toShift); return wrap(shiftLeft(param1, param2)); } protected abstract TFormulaInfo shiftLeft(TFormulaInfo pExtract, TFormulaInfo pExtract2); @Override public final BitvectorFormula concat(BitvectorFormula pNumber, BitvectorFormula pAppend) { TFormulaInfo param1 = extractInfo(pNumber); TFormulaInfo param2 = extractInfo(pAppend); return wrap(concat(param1, param2)); } protected abstract TFormulaInfo concat(TFormulaInfo number, TFormulaInfo pAppend); @Override public final BitvectorFormula extract(BitvectorFormula pNumber, int pMsb, int pLsb) { final int bitsize = getLength(pNumber); checkArgument(0 <= pLsb, "index out of bounds (negative index %s)", pLsb); checkArgument(pLsb <= pMsb, "invalid range (lsb %s larger than msb %s)", pLsb, pMsb); checkArgument(pMsb < bitsize, "index out of bounds (index %s beyond length %s)", pMsb, bitsize); return wrap(extract(extractInfo(pNumber), pMsb, pLsb)); } protected abstract TFormulaInfo extract(TFormulaInfo pNumber, int pMsb, int pLsb); @Override public final BitvectorFormula extend( BitvectorFormula pNumber, int pExtensionBits, boolean pSigned) { checkArgument(0 <= pExtensionBits, "can not extend a negative number of bits"); return wrap(extend(extractInfo(pNumber), pExtensionBits, pSigned)); } protected abstract TFormulaInfo extend(TFormulaInfo pNumber, int pExtensionBits, boolean pSigned); @Override public int getLength(BitvectorFormula pNumber) { FormulaType<BitvectorFormula> type = getFormulaCreator().getFormulaType(pNumber); return ((FormulaType.BitvectorType) type).getSize(); } @Override public final BooleanFormula distinct(List<BitvectorFormula> pBits) { // optimization if (pBits.size() <= 1) { return bmgr.makeTrue(); } else if (pBits.size() > 1L << getLength(pBits.iterator().next())) { return bmgr.makeFalse(); } else { return wrapBool(distinctImpl(Lists.transform(pBits, this::extractInfo))); } } protected TFormulaInfo distinctImpl(List<TFormulaInfo> pBits) { List<TFormulaInfo> lst = new ArrayList<>(); for (int i = 0; i < pBits.size(); i++) { for (int j = 0; j < i; j++) { lst.add(bmgr.not(equal(pBits.get(i), pBits.get(j)))); } } return bmgr.andImpl(lst); } }
12,968
33.584
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractBooleanFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collector; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaVisitor; import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements BooleanFormulaManager { private @Nullable BooleanFormula trueFormula = null; private @Nullable BooleanFormula falseFormula = null; protected AbstractBooleanFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator) { super(pCreator); } private BooleanFormula wrap(TFormulaInfo formulaInfo) { return getFormulaCreator().encapsulateBoolean(formulaInfo); } @Override public BooleanFormula makeVariable(String pVar) { checkVariableName(pVar); return wrap(makeVariableImpl(pVar)); } protected abstract TFormulaInfo makeVariableImpl(String pVar); @Override public BooleanFormula makeTrue() { if (trueFormula == null) { trueFormula = wrap(makeBooleanImpl(true)); } return trueFormula; } @Override public BooleanFormula makeFalse() { if (falseFormula == null) { falseFormula = wrap(makeBooleanImpl(false)); } return falseFormula; } protected abstract TFormulaInfo makeBooleanImpl(boolean value); @Override public BooleanFormula not(BooleanFormula pBits) { TFormulaInfo param1 = extractInfo(pBits); return wrap(not(param1)); } protected abstract TFormulaInfo not(TFormulaInfo pParam1); @Override public BooleanFormula and(BooleanFormula pBits1, BooleanFormula pBits2) { TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(and(param1, param2)); } protected abstract TFormulaInfo and(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula and(Collection<BooleanFormula> pBits) { switch (pBits.size()) { case 0: return makeTrue(); case 1: return pBits.iterator().next(); case 2: Iterator<BooleanFormula> it = pBits.iterator(); return and(it.next(), it.next()); default: return wrap(andImpl(Collections2.transform(pBits, this::extractInfo))); } } @Override public BooleanFormula and(BooleanFormula... pBits) { return and(Arrays.asList(pBits)); } /** * Create an n-ary conjunction. The default implementation delegates to {@link #and(Object, * Object)} and assumes that all simplifications are done by that method. This method can be * overridden, in which case it should filter out irrelevant operands. * * @param pParams A collection of at least 3 operands. * @return A term that is equivalent to a conjunction of pParams. */ protected TFormulaInfo andImpl(Collection<TFormulaInfo> pParams) { TFormulaInfo result = makeBooleanImpl(true); for (TFormulaInfo formula : ImmutableSet.copyOf(pParams)) { if (isFalse(formula)) { return formula; } result = and(result, formula); } return result; } @Override public final Collector<BooleanFormula, ?, BooleanFormula> toConjunction() { return Collectors.collectingAndThen(Collectors.toList(), this::and); } @Override public BooleanFormula or(BooleanFormula pBits1, BooleanFormula pBits2) { TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(or(param1, param2)); } @Override public BooleanFormula or(BooleanFormula... pBits) { return or(Arrays.asList(pBits)); } protected abstract TFormulaInfo or(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula xor(BooleanFormula pBits1, BooleanFormula pBits2) { TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(xor(param1, param2)); } @Override public BooleanFormula or(Collection<BooleanFormula> pBits) { switch (pBits.size()) { case 0: return makeFalse(); case 1: return pBits.iterator().next(); case 2: Iterator<BooleanFormula> it = pBits.iterator(); return or(it.next(), it.next()); default: return wrap(orImpl(Collections2.transform(pBits, this::extractInfo))); } } /** * Create an n-ary disjunction. The default implementation delegates to {@link #or(Object, * Object)} and assumes that all simplifications are done by that method. This method can be * overridden, in which case it should filter out irrelevant operands. * * @param pParams A collection of at least 3 operands. * @return A term that is equivalent to a disjunction of pParams. */ protected TFormulaInfo orImpl(Collection<TFormulaInfo> pParams) { TFormulaInfo result = makeBooleanImpl(false); for (TFormulaInfo formula : ImmutableSet.copyOf(pParams)) { if (isTrue(formula)) { return formula; } result = or(result, formula); } return result; } @Override public final Collector<BooleanFormula, ?, BooleanFormula> toDisjunction() { return Collectors.collectingAndThen(Collectors.toList(), this::or); } protected abstract TFormulaInfo xor(TFormulaInfo pParam1, TFormulaInfo pParam2); /** * Creates a formula representing an equivalence of the two arguments. * * @param pBits1 a Formula * @param pBits2 a Formula * @return {@code f1 <-> f2} */ @Override public final BooleanFormula equivalence(BooleanFormula pBits1, BooleanFormula pBits2) { TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(equivalence(param1, param2)); } protected abstract TFormulaInfo equivalence(TFormulaInfo bits1, TFormulaInfo bits2); @Override public final BooleanFormula implication(BooleanFormula pBits1, BooleanFormula pBits2) { TFormulaInfo param1 = extractInfo(pBits1); TFormulaInfo param2 = extractInfo(pBits2); return wrap(implication(param1, param2)); } protected TFormulaInfo implication(TFormulaInfo bits1, TFormulaInfo bits2) { return or(not(bits1), bits2); } @Override public final boolean isTrue(BooleanFormula pBits) { return isTrue(extractInfo(pBits)); } protected abstract boolean isTrue(TFormulaInfo bits); @Override public final boolean isFalse(BooleanFormula pBits) { return isFalse(extractInfo(pBits)); } protected abstract boolean isFalse(TFormulaInfo bits); /** * Creates a formula representing "IF cond THEN f1 ELSE f2". * * @param pBits a Formula * @param f1 a Formula * @param f2 a Formula * @return (IF cond THEN f1 ELSE f2) */ @Override public final <T extends Formula> T ifThenElse(BooleanFormula pBits, T f1, T f2) { FormulaType<T> t1 = getFormulaCreator().getFormulaType(f1); FormulaType<T> t2 = getFormulaCreator().getFormulaType(f2); checkArgument( t1.equals(t2), "Cannot create if-then-else formula with branches of different types: " + "%s is of type %s; %s is of type %s", f1, t1, f2, t2); TFormulaInfo result = ifThenElse(extractInfo(pBits), extractInfo(f1), extractInfo(f2)); return getFormulaCreator().encapsulate(t1, result); } protected abstract TFormulaInfo ifThenElse(TFormulaInfo cond, TFormulaInfo f1, TFormulaInfo f2); @Override public <R> R visit(BooleanFormula pFormula, BooleanFormulaVisitor<R> visitor) { return formulaCreator.visit(pFormula, new DelegatingFormulaVisitor<>(visitor)); } @Override public void visitRecursively( BooleanFormula pF, BooleanFormulaVisitor<TraversalProcess> pFormulaVisitor) { formulaCreator.visitRecursively( new DelegatingFormulaVisitor<>(pFormulaVisitor), pF, p -> p instanceof BooleanFormula); } @Override public BooleanFormula transformRecursively( BooleanFormula f, BooleanFormulaTransformationVisitor pVisitor) { return formulaCreator.transformRecursively( new DelegatingFormulaVisitor<>(pVisitor), f, p -> p instanceof BooleanFormula); } private class DelegatingFormulaVisitor<R> implements FormulaVisitor<R> { private final BooleanFormulaVisitor<R> delegate; DelegatingFormulaVisitor(BooleanFormulaVisitor<R> pDelegate) { delegate = pDelegate; } @Override public R visitFreeVariable(Formula f, String name) { // Only boolean formulas can appear here. assert f instanceof BooleanFormula; BooleanFormula casted = (BooleanFormula) f; return delegate.visitAtom( casted, FunctionDeclarationImpl.of( name, FunctionDeclarationKind.VAR, ImmutableList.of(), FormulaType.BooleanType, formulaCreator.getBooleanVarDeclaration(casted))); } @Override public R visitBoundVariable(Formula f, int deBruijnIdx) { // Only boolean formulas can appear here. assert f instanceof BooleanFormula; return delegate.visitBoundVar((BooleanFormula) f, deBruijnIdx); } @Override public R visitConstant(Formula f, Object value) { checkState(value instanceof Boolean); return delegate.visitConstant((boolean) value); } private List<BooleanFormula> getBoolArgs(List<Formula> args) { checkState(Iterables.all(args, arg -> arg instanceof BooleanFormula)); @SuppressWarnings("unchecked") List<BooleanFormula> out = (List<BooleanFormula>) (List<?>) args; return out; } @Override public R visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { switch (functionDeclaration.getKind()) { case AND: R out = delegate.visitAnd(getBoolArgs(args)); return out; case NOT: checkState(args.size() == 1); Formula arg = args.get(0); checkArgument(arg instanceof BooleanFormula); return delegate.visitNot((BooleanFormula) arg); case OR: R out2 = delegate.visitOr(getBoolArgs(args)); return out2; case IFF: checkState(args.size() == 2); Formula a = args.get(0); Formula b = args.get(1); checkState(a instanceof BooleanFormula && b instanceof BooleanFormula); R out3 = delegate.visitEquivalence((BooleanFormula) a, (BooleanFormula) b); return out3; case EQ: if (args.size() == 2 && args.get(0) instanceof BooleanFormula && args.get(1) instanceof BooleanFormula) { return delegate.visitEquivalence( (BooleanFormula) args.get(0), (BooleanFormula) args.get(1)); } else { return delegate.visitAtom( (BooleanFormula) f, toBooleanDeclaration(functionDeclaration)); } case ITE: checkArgument(args.size() == 3); Formula ifC = args.get(0); Formula then = args.get(1); Formula elseC = args.get(2); checkState( ifC instanceof BooleanFormula && then instanceof BooleanFormula && elseC instanceof BooleanFormula); return delegate.visitIfThenElse( (BooleanFormula) ifC, (BooleanFormula) then, (BooleanFormula) elseC); case XOR: checkArgument(args.size() == 2); Formula a1 = args.get(0); Formula a2 = args.get(1); checkState(a1 instanceof BooleanFormula && a2 instanceof BooleanFormula); return delegate.visitXor((BooleanFormula) a1, (BooleanFormula) a2); case IMPLIES: checkArgument(args.size() == 2); Formula b1 = args.get(0); Formula b2 = args.get(1); checkArgument(b1 instanceof BooleanFormula && b2 instanceof BooleanFormula); return delegate.visitImplication((BooleanFormula) b1, (BooleanFormula) b2); default: return delegate.visitAtom((BooleanFormula) f, toBooleanDeclaration(functionDeclaration)); } } @Override public R visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula body) { return delegate.visitQuantifier(quantifier, f, boundVariables, body); } @SuppressWarnings("unchecked") private FunctionDeclaration<BooleanFormula> toBooleanDeclaration(FunctionDeclaration<?> decl) { return (FunctionDeclaration<BooleanFormula>) decl; } } @Override public Set<BooleanFormula> toConjunctionArgs(BooleanFormula f, boolean flatten) { if (flatten) { return asFuncRecursive(f, conjunctionFinder); } return formulaCreator.visit(f, conjunctionFinder); } @Override public Set<BooleanFormula> toDisjunctionArgs(BooleanFormula f, boolean flatten) { if (flatten) { return asFuncRecursive(f, disjunctionFinder); } return formulaCreator.visit(f, disjunctionFinder); } /** Optimized non-recursive flattening implementation. */ private Set<BooleanFormula> asFuncRecursive( BooleanFormula f, FormulaVisitor<Set<BooleanFormula>> visitor) { ImmutableSet.Builder<BooleanFormula> output = ImmutableSet.builder(); Deque<BooleanFormula> toProcess = new ArrayDeque<>(); Map<BooleanFormula, Set<BooleanFormula>> cache = new HashMap<>(); toProcess.add(f); while (!toProcess.isEmpty()) { BooleanFormula s = toProcess.pop(); Set<BooleanFormula> out = cache.computeIfAbsent(s, ss -> formulaCreator.visit(ss, visitor)); if (out.size() == 1 && s.equals(out.iterator().next())) { output.add(s); } for (BooleanFormula arg : out) { if (cache.get(arg) == null) { // Wasn't processed yet. toProcess.add(arg); } } } return output.build(); } private final FormulaVisitor<Set<BooleanFormula>> conjunctionFinder = new DefaultFormulaVisitor<>() { @Override protected Set<BooleanFormula> visitDefault(Formula f) { assert f instanceof BooleanFormula; BooleanFormula bf = (BooleanFormula) f; if (isTrue(bf)) { return ImmutableSet.of(); } return ImmutableSet.of((BooleanFormula) f); } @SuppressWarnings("unchecked") @Override public Set<BooleanFormula> visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { if (functionDeclaration.getKind() == FunctionDeclarationKind.AND) { return ImmutableSet.copyOf((List<BooleanFormula>) (List<?>) args); } return visitDefault(f); } }; /** * Optimized, but ugly, implementation of argument extraction. Avoids extra visitor instantiation. */ private final FormulaVisitor<Set<BooleanFormula>> disjunctionFinder = new DefaultFormulaVisitor<>() { @Override protected Set<BooleanFormula> visitDefault(Formula f) { assert f instanceof BooleanFormula; BooleanFormula bf = (BooleanFormula) f; if (isFalse(bf)) { return ImmutableSet.of(); } return ImmutableSet.of((BooleanFormula) f); } @SuppressWarnings("unchecked") @Override public Set<BooleanFormula> visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { if (functionDeclaration.getKind() == FunctionDeclarationKind.OR) { return ImmutableSet.copyOf((List<BooleanFormula>) (List<?>) args); } return visitDefault(f); } }; }
17,336
33.127953
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractEnumerationFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2023 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormula; import org.sosy_lab.java_smt.api.EnumerationFormulaManager; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.EnumerationFormulaType; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractEnumerationFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements EnumerationFormulaManager { /** The class 'EnumType' is just a plain internal value-holding class. */ protected class EnumType { private final EnumerationFormulaType enumerationFormulaType; private final TType nativeType; private final ImmutableMap<String, TFormulaInfo> constants; public EnumType( EnumerationFormulaType pEnumerationFormulaType, TType pNativeType, ImmutableMap<String, TFormulaInfo> pConstants) { enumerationFormulaType = pEnumerationFormulaType; nativeType = pNativeType; constants = pConstants; } public EnumerationFormulaType getEnumerationFormulaType() { return enumerationFormulaType; } public boolean hasConstants(String name) { return constants.containsKey(name); } } protected final Map<String, EnumType> enumerations = new LinkedHashMap<>(); protected AbstractEnumerationFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pFormulaCreator) { super(pFormulaCreator); } private EnumerationFormula wrap(TFormulaInfo pTerm) { return getFormulaCreator().encapsulateEnumeration(pTerm); } private void checkSameEnumerationType(EnumerationFormula pF1, EnumerationFormula pF2) { final FormulaType<?> type1 = formulaCreator.getFormulaType(pF1); final FormulaType<?> type2 = formulaCreator.getFormulaType(pF2); checkArgument(type1 instanceof EnumerationFormulaType); checkArgument(type2 instanceof EnumerationFormulaType); checkArgument( type1.equals(type2), "Can't compare element of type %s with element of type %s.", type1, type2); } @Override public EnumerationFormulaType declareEnumeration(String pName, Set<String> pElementNames) { checkVariableName(pName); return declareEnumerationImpl(pName, pElementNames); } protected EnumerationFormulaType declareEnumerationImpl(String pName, Set<String> pElementNames) { final EnumerationFormulaType type = FormulaType.getEnumerationType(pName, pElementNames); EnumType existingType = enumerations.get(pName); if (existingType == null) { enumerations.put(pName, declareEnumeration0(type)); } else { Preconditions.checkArgument( type.equals(existingType.getEnumerationFormulaType()), "Enumeration type '%s' is already declared as '%s'.", type, existingType.getEnumerationFormulaType()); } return type; } protected abstract EnumType declareEnumeration0(EnumerationFormulaType pType); @Override public EnumerationFormula makeConstant(String pName, EnumerationFormulaType pType) { Preconditions.checkArgument( pType.getElements().contains(pName), "Constant '%s' is not available in the enumeration type '%s'", pName, pType); return wrap(makeConstantImpl(pName, pType)); } protected TFormulaInfo makeConstantImpl(String pName, EnumerationFormulaType pType) { return checkNotNull(enumerations.get(pType.getName()).constants.get(pName)); } @Override public EnumerationFormula makeVariable(String pVar, EnumerationFormulaType pType) { checkVariableName(pVar); return wrap(makeVariableImpl(pVar, pType)); } protected TFormulaInfo makeVariableImpl(String pVar, EnumerationFormulaType pType) { return getFormulaCreator().makeVariable(enumerations.get(pType.getName()).nativeType, pVar); } @Override public BooleanFormula equivalence(EnumerationFormula pF1, EnumerationFormula pF2) { this.checkSameEnumerationType(pF1, pF2); return wrapBool(equivalenceImpl(extractInfo(pF1), extractInfo(pF2))); } protected abstract TFormulaInfo equivalenceImpl(TFormulaInfo pF1, TFormulaInfo pF2); }
4,912
35.93985
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractEvaluator.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import java.math.BigInteger; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormula; import org.sosy_lab.java_smt.api.Evaluator; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; import org.sosy_lab.java_smt.api.StringFormula; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractEvaluator<TFormulaInfo, TType, TEnv> implements Evaluator { private final AbstractProver<?> prover; protected final FormulaCreator<TFormulaInfo, TType, TEnv, ?> creator; private boolean closed = false; protected AbstractEvaluator( AbstractProver<?> pProver, FormulaCreator<TFormulaInfo, TType, TEnv, ?> creator) { this.prover = pProver; this.creator = creator; } @SuppressWarnings("unchecked") @Nullable @Override public final <T extends Formula> T eval(T f) { Preconditions.checkState(!isClosed()); TFormulaInfo evaluation = evalImpl(creator.extractInfo(f)); return evaluation == null ? null : (T) creator.encapsulateWithTypeOf(evaluation); } @Nullable @Override public final BigInteger evaluate(IntegerFormula f) { Preconditions.checkState(!isClosed()); return (BigInteger) evaluateImpl(creator.extractInfo(f)); } @Nullable @Override public Rational evaluate(RationalFormula f) { Object value = evaluateImpl(creator.extractInfo(f)); if (value instanceof BigInteger) { // We simplified the value internally. Here, we need to convert it back to Rational. return Rational.ofBigInteger((BigInteger) value); } else { return (Rational) value; } } @Nullable @Override public final Boolean evaluate(BooleanFormula f) { Preconditions.checkState(!isClosed()); return (Boolean) evaluateImpl(creator.extractInfo(f)); } @Nullable @Override public final String evaluate(StringFormula f) { Preconditions.checkState(!isClosed()); return (String) evaluateImpl(creator.extractInfo(f)); } @Nullable @Override public final String evaluate(EnumerationFormula f) { Preconditions.checkState(!isClosed()); return (String) evaluateImpl(creator.extractInfo(f)); } @Nullable @Override public final BigInteger evaluate(BitvectorFormula f) { Preconditions.checkState(!isClosed()); return (BigInteger) evaluateImpl(creator.extractInfo(f)); } @Nullable @Override public final Object evaluate(Formula f) { Preconditions.checkState(!isClosed()); Preconditions.checkArgument( !(f instanceof ArrayFormula), "cannot compute a simple constant evaluation for an array-formula"); return evaluateImpl(creator.extractInfo(f)); } /** * Simplify the given formula and replace all symbols with their model values. If a symbol is not * set in the model and evaluation aborts, return <code>null</code>. */ @Nullable protected abstract TFormulaInfo evalImpl(TFormulaInfo formula); /** * Simplify the given formula and replace all symbols with their model values. If a symbol is not * set in the model and evaluation aborts, return <code>null</code>. Afterwards convert the * formula into a Java object as far as possible, i.e., try to match a primitive or simple type. */ @Nullable protected final Object evaluateImpl(TFormulaInfo f) { Preconditions.checkState(!isClosed()); TFormulaInfo evaluatedF = evalImpl(f); return evaluatedF == null ? null : creator.convertValue(f, evaluatedF); } protected boolean isClosed() { return closed; } @Override public void close() { if (prover != null) { // can be NULL for testing prover.unregisterEvaluator(this); } closed = true; } }
4,325
31.044444
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractFloatingPointFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.base.Preconditions; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.FloatingPointFormula; import org.sosy_lab.java_smt.api.FloatingPointFormulaManager; import org.sosy_lab.java_smt.api.FloatingPointRoundingMode; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; /** * Similar to the other Abstract*FormulaManager classes in this package, this class serves as a * helper for implementing {@link FloatingPointFormulaManager}. It handles all the unwrapping and * wrapping from and to the {@link Formula} instances, such that the concrete class needs to handle * only its own internal types. * * <p>For {@link #multiply(FloatingPointFormula, FloatingPointFormula)}, and {@link * #divide(FloatingPointFormula, FloatingPointFormula)} this class even offers an implementation * based on UFs. Sub-classes are supposed to override them if they can implement these operations * more precisely (for example multiplication with constants should be supported by all solvers and * implemented by all sub-classes). */ @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractFloatingPointFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements FloatingPointFormulaManager { private final Map<FloatingPointRoundingMode, TFormulaInfo> roundingModes; protected AbstractFloatingPointFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator) { super(pCreator); roundingModes = new HashMap<>(); } protected abstract TFormulaInfo getDefaultRoundingMode(); protected abstract TFormulaInfo getRoundingModeImpl( FloatingPointRoundingMode pFloatingPointRoundingMode); private TFormulaInfo getRoundingMode(FloatingPointRoundingMode pFloatingPointRoundingMode) { return roundingModes.computeIfAbsent(pFloatingPointRoundingMode, this::getRoundingModeImpl); } protected FloatingPointFormula wrap(TFormulaInfo pTerm) { return getFormulaCreator().encapsulateFloatingPoint(pTerm); } @Override public FloatingPointFormula makeNumber(Rational n, FormulaType.FloatingPointType type) { return wrap(makeNumberImpl(n.toString(), type, getDefaultRoundingMode())); } @Override public FloatingPointFormula makeNumber( Rational n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap(makeNumberImpl(n.toString(), type, getRoundingMode(pFloatingPointRoundingMode))); } @Override public FloatingPointFormula makeNumber(double n, FormulaType.FloatingPointType type) { return wrap(makeNumberImpl(n, type, getDefaultRoundingMode())); } @Override public FloatingPointFormula makeNumber( double n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap(makeNumberImpl(n, type, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo makeNumberImpl( double n, FormulaType.FloatingPointType type, TFormulaInfo pFloatingPointRoundingMode); @Override public FloatingPointFormula makeNumber(BigDecimal n, FormulaType.FloatingPointType type) { return wrap(makeNumberImpl(n, type, getDefaultRoundingMode())); } @Override public FloatingPointFormula makeNumber( BigDecimal n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap(makeNumberImpl(n, type, getRoundingMode(pFloatingPointRoundingMode))); } protected TFormulaInfo makeNumberImpl( BigDecimal n, FormulaType.FloatingPointType type, TFormulaInfo pFloatingPointRoundingMode) { return makeNumberImpl(n.toPlainString(), type, pFloatingPointRoundingMode); } @Override public FloatingPointFormula makeNumber(String n, FormulaType.FloatingPointType type) { return wrap(makeNumberImpl(n, type, getDefaultRoundingMode())); } @Override public FloatingPointFormula makeNumber( String n, FloatingPointType type, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap(makeNumberImpl(n, type, getRoundingMode(pFloatingPointRoundingMode))); } /** directly catch the most common special String constants. */ protected TFormulaInfo makeNumberImpl( String n, FormulaType.FloatingPointType type, TFormulaInfo pFloatingPointRoundingMode) { if (n.startsWith("+")) { n = n.substring(1); } switch (n) { case "NaN": case "-NaN": return makeNaNImpl(type); case "Infinity": return makePlusInfinityImpl(type); case "-Infinity": return makeMinusInfinityImpl(type); default: return makeNumberAndRound(n, type, pFloatingPointRoundingMode); } } protected static boolean isNegativeZero(Double pN) { Preconditions.checkNotNull(pN); return Double.valueOf("-0.0").equals(pN); } protected abstract TFormulaInfo makeNumberAndRound( String pN, FloatingPointType pType, TFormulaInfo pFloatingPointRoundingMode); @Override public FloatingPointFormula makeVariable(String pVar, FormulaType.FloatingPointType pType) { checkVariableName(pVar); return wrap(makeVariableImpl(pVar, pType)); } protected abstract TFormulaInfo makeVariableImpl( String pVar, FormulaType.FloatingPointType pType); @Override public FloatingPointFormula makePlusInfinity(FormulaType.FloatingPointType pType) { return wrap(makePlusInfinityImpl(pType)); } protected abstract TFormulaInfo makePlusInfinityImpl(FormulaType.FloatingPointType pType); @Override public FloatingPointFormula makeMinusInfinity(FormulaType.FloatingPointType pType) { return wrap(makeMinusInfinityImpl(pType)); } protected abstract TFormulaInfo makeMinusInfinityImpl(FormulaType.FloatingPointType pType); @Override public FloatingPointFormula makeNaN(FormulaType.FloatingPointType pType) { return wrap(makeNaNImpl(pType)); } protected abstract TFormulaInfo makeNaNImpl(FormulaType.FloatingPointType pType); @Override public <T extends Formula> T castTo( FloatingPointFormula pNumber, boolean pSigned, FormulaType<T> pTargetType) { return getFormulaCreator() .encapsulate( pTargetType, castToImpl(extractInfo(pNumber), pSigned, pTargetType, getDefaultRoundingMode())); } @Override public <T extends Formula> T castTo( FloatingPointFormula number, boolean pSigned, FormulaType<T> targetType, FloatingPointRoundingMode pFloatingPointRoundingMode) { return getFormulaCreator() .encapsulate( targetType, castToImpl( extractInfo(number), pSigned, targetType, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo castToImpl( TFormulaInfo pNumber, boolean pSigned, FormulaType<?> pTargetType, TFormulaInfo pRoundingMode); @Override public FloatingPointFormula castFrom( Formula pNumber, boolean pSigned, FormulaType.FloatingPointType pTargetType) { return wrap(castFromImpl(extractInfo(pNumber), pSigned, pTargetType, getDefaultRoundingMode())); } @Override public FloatingPointFormula castFrom( Formula number, boolean signed, FloatingPointType targetType, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap( castFromImpl( extractInfo(number), signed, targetType, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo castFromImpl( TFormulaInfo pNumber, boolean pSigned, FormulaType.FloatingPointType pTargetType, TFormulaInfo pRoundingMode); @Override public FloatingPointFormula fromIeeeBitvector( BitvectorFormula pNumber, FloatingPointType pTargetType) { return wrap(fromIeeeBitvectorImpl(extractInfo(pNumber), pTargetType)); } protected abstract TFormulaInfo fromIeeeBitvectorImpl( TFormulaInfo pNumber, FloatingPointType pTargetType); @Override public BitvectorFormula toIeeeBitvector(FloatingPointFormula pNumber) { return getFormulaCreator().encapsulateBitvector(toIeeeBitvectorImpl(extractInfo(pNumber))); } protected abstract TFormulaInfo toIeeeBitvectorImpl(TFormulaInfo pNumber); @Override public FloatingPointFormula negate(FloatingPointFormula pNumber) { TFormulaInfo param1 = extractInfo(pNumber); return wrap(negate(param1)); } protected abstract TFormulaInfo negate(TFormulaInfo pParam1); @Override public FloatingPointFormula abs(FloatingPointFormula pNumber) { TFormulaInfo param1 = extractInfo(pNumber); return wrap(abs(param1)); } protected abstract TFormulaInfo abs(TFormulaInfo pParam1); @Override public FloatingPointFormula max(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { return wrap(max(extractInfo(pNumber1), extractInfo(pNumber2))); } protected abstract TFormulaInfo max(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public FloatingPointFormula min(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { return wrap(min(extractInfo(pNumber1), extractInfo(pNumber2))); } protected abstract TFormulaInfo min(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public FloatingPointFormula sqrt(FloatingPointFormula pNumber) { return wrap(sqrt(extractInfo(pNumber), getDefaultRoundingMode())); } @Override public FloatingPointFormula sqrt( FloatingPointFormula number, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap(sqrt(extractInfo(number), getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo sqrt(TFormulaInfo pNumber, TFormulaInfo pRoundingMode); @Override public FloatingPointFormula add(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(add(param1, param2, getDefaultRoundingMode())); } @Override public FloatingPointFormula add( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode) { return wrap( add( extractInfo(number1), extractInfo(number2), getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo add( TFormulaInfo pParam1, TFormulaInfo pParam2, TFormulaInfo pRoundingMode); @Override public FloatingPointFormula subtract( FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(subtract(param1, param2, getDefaultRoundingMode())); } @Override public FloatingPointFormula subtract( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode) { TFormulaInfo param1 = extractInfo(number1); TFormulaInfo param2 = extractInfo(number2); return wrap(subtract(param1, param2, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo subtract( TFormulaInfo pParam1, TFormulaInfo pParam2, TFormulaInfo pFloatingPointRoundingMode); @Override public FloatingPointFormula divide(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(divide(param1, param2, getDefaultRoundingMode())); } @Override public FloatingPointFormula divide( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode) { TFormulaInfo param1 = extractInfo(number1); TFormulaInfo param2 = extractInfo(number2); return wrap(divide(param1, param2, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo divide( TFormulaInfo pParam1, TFormulaInfo pParam2, TFormulaInfo pFloatingPointRoundingMode); @Override public FloatingPointFormula multiply( FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(multiply(param1, param2, getDefaultRoundingMode())); } @Override public FloatingPointFormula multiply( FloatingPointFormula number1, FloatingPointFormula number2, FloatingPointRoundingMode pFloatingPointRoundingMode) { TFormulaInfo param1 = extractInfo(number1); TFormulaInfo param2 = extractInfo(number2); return wrap(multiply(param1, param2, getRoundingMode(pFloatingPointRoundingMode))); } protected abstract TFormulaInfo multiply( TFormulaInfo pParam1, TFormulaInfo pParam2, TFormulaInfo pFloatingPointRoundingMode); @Override public BooleanFormula assignment(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(assignment(param1, param2)); } protected abstract TFormulaInfo assignment(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula equalWithFPSemantics( FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(equalWithFPSemantics(param1, param2)); } protected abstract TFormulaInfo equalWithFPSemantics(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterThan(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterThan(param1, param2)); } protected abstract TFormulaInfo greaterThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterOrEquals( FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterOrEquals(param1, param2)); } protected abstract TFormulaInfo greaterOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessThan(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessThan(param1, param2)); } protected abstract TFormulaInfo lessThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessOrEquals(FloatingPointFormula pNumber1, FloatingPointFormula pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessOrEquals(param1, param2)); } protected abstract TFormulaInfo lessOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula isNaN(FloatingPointFormula pNumber) { return wrapBool(isNaN(extractInfo(pNumber))); } protected abstract TFormulaInfo isNaN(TFormulaInfo pParam); @Override public BooleanFormula isInfinity(FloatingPointFormula pNumber) { return wrapBool(isInfinity(extractInfo(pNumber))); } protected abstract TFormulaInfo isInfinity(TFormulaInfo pParam); @Override public BooleanFormula isZero(FloatingPointFormula pNumber) { return wrapBool(isZero(extractInfo(pNumber))); } protected abstract TFormulaInfo isZero(TFormulaInfo pParam); @Override public BooleanFormula isSubnormal(FloatingPointFormula pNumber) { return wrapBool(isSubnormal(extractInfo(pNumber))); } protected abstract TFormulaInfo isSubnormal(TFormulaInfo pParam); @Override public BooleanFormula isNormal(FloatingPointFormula pNumber) { return wrapBool(isNormal(extractInfo(pNumber))); } protected abstract TFormulaInfo isNormal(TFormulaInfo pParam); @Override public BooleanFormula isNegative(FloatingPointFormula pNumber) { return wrapBool(isNegative(extractInfo(pNumber))); } protected abstract TFormulaInfo isNegative(TFormulaInfo pParam); @Override public FloatingPointFormula round( FloatingPointFormula pFormula, FloatingPointRoundingMode pRoundingMode) { return wrap(round(extractInfo(pFormula), pRoundingMode)); } protected abstract TFormulaInfo round( TFormulaInfo pFormula, FloatingPointRoundingMode pRoundingMode); }
17,309
34.326531
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractFormula.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkNotNull; import com.google.errorprone.annotations.Immutable; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormula; import org.sosy_lab.java_smt.api.FloatingPointFormula; import org.sosy_lab.java_smt.api.FloatingPointRoundingModeFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.StringFormula; /** * A Formula represented as a TFormulaInfo object. * * @param <TFormulaInfo> the solver specific type. */ @Immutable(containerOf = "TFormulaInfo") @SuppressWarnings("ClassTypeParameterName") abstract class AbstractFormula<TFormulaInfo> implements Formula { private final TFormulaInfo formulaInfo; private AbstractFormula(TFormulaInfo formulaInfo) { this.formulaInfo = checkNotNull(formulaInfo); } @Override public final boolean equals(@Nullable Object o) { if (o == this) { return true; } if (!(o instanceof AbstractFormula)) { return false; } Object otherFormulaInfo = ((AbstractFormula<?>) o).formulaInfo; return formulaInfo == otherFormulaInfo || formulaInfo.equals(otherFormulaInfo); } final TFormulaInfo getFormulaInfo() { return formulaInfo; } @Override public final int hashCode() { return formulaInfo.hashCode(); } @Override public final String toString() { return formulaInfo.toString(); } /** Simple ArrayFormula implementation. */ static final class ArrayFormulaImpl<TI extends Formula, TE extends Formula, TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements ArrayFormula<TI, TE> { private final FormulaType<TI> indexType; private final FormulaType<TE> elementType; ArrayFormulaImpl(TFormulaInfo info, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) { super(info); this.indexType = checkNotNull(pIndexType); this.elementType = checkNotNull(pElementType); } public FormulaType<TI> getIndexType() { return indexType; } public FormulaType<TE> getElementType() { return elementType; } } /** Simple BooleanFormula implementation. Just tracing the size and the sign-treatment */ static final class BitvectorFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements BitvectorFormula { BitvectorFormulaImpl(TFormulaInfo info) { super(info); } } /** Simple FloatingPointFormula implementation. */ static final class FloatingPointFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements FloatingPointFormula { FloatingPointFormulaImpl(TFormulaInfo info) { super(info); } } /** Simple FloatingPointRoundingModeFormula implementation. */ static final class FloatingPointRoundingModeFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements FloatingPointRoundingModeFormula { FloatingPointRoundingModeFormulaImpl(TFormulaInfo info) { super(info); } } /** Simple BooleanFormula implementation. */ static final class BooleanFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements BooleanFormula { BooleanFormulaImpl(TFormulaInfo pT) { super(pT); } } /** Simple IntegerFormula implementation. */ static final class IntegerFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements IntegerFormula { IntegerFormulaImpl(TFormulaInfo pTerm) { super(pTerm); } } /** Simple RationalFormula implementation. */ static final class RationalFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements RationalFormula { RationalFormulaImpl(TFormulaInfo pTerm) { super(pTerm); } } /** Simple StringFormula implementation. */ static final class StringFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements StringFormula { StringFormulaImpl(TFormulaInfo pT) { super(pT); } } /** Simple RegexFormula implementation. */ static final class RegexFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements RegexFormula { RegexFormulaImpl(TFormulaInfo pT) { super(pT); } } /** Simple EnumerationFormula implementation. */ static final class EnumerationFormulaImpl<TFormulaInfo> extends AbstractFormula<TFormulaInfo> implements EnumerationFormula { EnumerationFormulaImpl(TFormulaInfo pT) { super(pT); } } }
5,150
30.601227
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.Appender; import org.sosy_lab.java_smt.api.ArrayFormulaManager; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormulaManager; import org.sosy_lab.java_smt.api.FloatingPointFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; import org.sosy_lab.java_smt.api.FormulaType.BitvectorType; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.IntegerFormulaManager; import org.sosy_lab.java_smt.api.RationalFormulaManager; import org.sosy_lab.java_smt.api.SLFormulaManager; import org.sosy_lab.java_smt.api.StringFormulaManager; import org.sosy_lab.java_smt.api.Tactic; import org.sosy_lab.java_smt.api.visitors.FormulaTransformationVisitor; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; import org.sosy_lab.java_smt.basicimpl.tactics.NNFVisitor; import org.sosy_lab.java_smt.utils.SolverUtils; /** * Simplifies building a solver from the specific theories. * * @param <TFormulaInfo> The solver specific type. */ @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements FormulaManager { /** * Avoid using basic mathematical or logical operators of SMT-LIB2 as names for symbols. * * <p>We do not accept some names as identifiers for variables or UFs, because they easily * misguide the user. Most solvers even would allow such identifiers directly, currently only * SMTInterpol has problems with some of them. For consistency, we disallow those names for all * solvers. */ @VisibleForTesting public static final ImmutableSet<String> BASIC_OPERATORS = ImmutableSet.of("!", "+", "-", "*", "/", "%", "=", "<", ">", "<=", ">="); /** * Avoid using basic keywords of SMT-LIB2 as names for symbols. * * <p>We do not accept some names as identifiers for variables or UFs, because they easily * misguide the user. Most solvers even would allow such identifiers directly, currently only * SMTInterpol has problems with some of them. For consistency, we disallow those names for all * solvers. */ @VisibleForTesting public static final ImmutableSet<String> SMTLIB2_KEYWORDS = ImmutableSet.of("true", "false", "and", "or", "select", "store", "xor", "distinct", "let"); /** * Avoid using escape characters of SMT-LIB2 as part of names for symbols. * * <p>We do not accept some names as identifiers for variables or UFs, because they easily * misguide the user. Most solvers even would allow such identifiers directly, currently only * SMTInterpol has problems with some of them. For consistency, we disallow those names for all * solvers. */ private static final CharMatcher DISALLOWED_CHARACTERS = CharMatcher.anyOf("|\\"); /** Mapping of disallowed char to their escaped counterparts. */ /* Keep this map in sync with {@link #DISALLOWED_CHARACTERS}. * Counterparts can be any unique string. For optimization, we could even use plain chars. */ @VisibleForTesting public static final ImmutableBiMap<Character, String> DISALLOWED_CHARACTER_REPLACEMENT = ImmutableBiMap.of('|', "pipe", '\\', "backslash"); private static final char ESCAPE = '$'; // just some allowed symbol, can be any char private final @Nullable AbstractArrayFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> arrayManager; private final AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> booleanManager; private final @Nullable IntegerFormulaManager integerManager; private final @Nullable RationalFormulaManager rationalManager; private final @Nullable AbstractBitvectorFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> bitvectorManager; private final @Nullable AbstractFloatingPointFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> floatingPointManager; private final AbstractUFManager<TFormulaInfo, ?, TType, TEnv> functionManager; private final @Nullable AbstractQuantifiedFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> quantifiedManager; private final @Nullable AbstractSLFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> slManager; private final @Nullable AbstractStringFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> strManager; private final @Nullable AbstractEnumerationFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> enumManager; private final FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> formulaCreator; /** Builds a solver from the given theory implementations. */ @SuppressWarnings("checkstyle:parameternumber") protected AbstractFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pFormulaCreator, AbstractUFManager<TFormulaInfo, ?, TType, TEnv> functionManager, AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> booleanManager, @Nullable IntegerFormulaManager pIntegerManager, @Nullable RationalFormulaManager pRationalManager, @Nullable AbstractBitvectorFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> bitvectorManager, @Nullable AbstractFloatingPointFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> floatingPointManager, @Nullable AbstractQuantifiedFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> quantifiedManager, @Nullable AbstractArrayFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> arrayManager, @Nullable AbstractSLFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> slManager, @Nullable AbstractStringFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> strManager, @Nullable AbstractEnumerationFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> enumManager) { this.arrayManager = arrayManager; this.quantifiedManager = quantifiedManager; this.functionManager = checkNotNull(functionManager, "function manager needed"); this.booleanManager = checkNotNull(booleanManager, "boolean manager needed"); this.integerManager = pIntegerManager; this.rationalManager = pRationalManager; this.bitvectorManager = bitvectorManager; this.floatingPointManager = floatingPointManager; this.slManager = slManager; this.strManager = strManager; this.enumManager = enumManager; this.formulaCreator = pFormulaCreator; checkArgument( booleanManager.getFormulaCreator() == formulaCreator && functionManager.getFormulaCreator() == formulaCreator && !(bitvectorManager != null && bitvectorManager.getFormulaCreator() != formulaCreator) && !(floatingPointManager != null && floatingPointManager.getFormulaCreator() != formulaCreator) && !(quantifiedManager != null && quantifiedManager.getFormulaCreator() != formulaCreator), "The creator instances must match across the managers!"); } public final FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> getFormulaCreator() { return formulaCreator; } @Override public IntegerFormulaManager getIntegerFormulaManager() { if (integerManager == null) { throw new UnsupportedOperationException("Solver does not support integer theory"); } return integerManager; } @Override public RationalFormulaManager getRationalFormulaManager() { if (rationalManager == null) { throw new UnsupportedOperationException("Solver does not support rationals theory"); } return rationalManager; } @Override public AbstractBooleanFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> getBooleanFormulaManager() { return booleanManager; } @Override public AbstractBitvectorFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> getBitvectorFormulaManager() { if (bitvectorManager == null) { throw new UnsupportedOperationException("Solver does not support bitvector theory"); } return bitvectorManager; } @Override public FloatingPointFormulaManager getFloatingPointFormulaManager() { if (floatingPointManager == null) { throw new UnsupportedOperationException("Solver does not support floating point theory"); } return floatingPointManager; } @Override public AbstractUFManager<TFormulaInfo, ?, TType, TEnv> getUFManager() { return functionManager; } @Override public SLFormulaManager getSLFormulaManager() { if (slManager == null) { throw new UnsupportedOperationException("Solver does not support separation logic theory"); } return slManager; } @Override public AbstractQuantifiedFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> getQuantifiedFormulaManager() { if (quantifiedManager == null) { throw new UnsupportedOperationException("Solver does not support quantification"); } return quantifiedManager; } @Override public ArrayFormulaManager getArrayFormulaManager() { if (arrayManager == null) { throw new UnsupportedOperationException("Solver does not support arrays"); } return arrayManager; } @Override public StringFormulaManager getStringFormulaManager() { if (strManager == null) { throw new UnsupportedOperationException("Solver does not support string theory"); } return strManager; } @Override public EnumerationFormulaManager getEnumerationFormulaManager() { if (enumManager == null) { throw new UnsupportedOperationException("Solver does not support enumeration theory"); } return enumManager; } public abstract Appender dumpFormula(TFormulaInfo t); @Override public Appender dumpFormula(BooleanFormula t) { return dumpFormula(formulaCreator.extractInfo(t)); } @Override public final <T extends Formula> FormulaType<T> getFormulaType(T formula) { return formulaCreator.getFormulaType(checkNotNull(formula)); } // Utility methods that are handy for subclasses public final TEnv getEnvironment() { return getFormulaCreator().getEnv(); } public final TFormulaInfo extractInfo(Formula f) { return formulaCreator.extractInfo(f); } @Override public BooleanFormula applyTactic(BooleanFormula f, Tactic tactic) throws InterruptedException { switch (tactic) { case ACKERMANNIZATION: return applyUFEImpl(f); case NNF: return applyNNFImpl(f); case TSEITIN_CNF: return applyCNFImpl(f); case QE_LIGHT: return applyQELightImpl(f); default: throw new UnsupportedOperationException("Unexpected enum value"); } } /** * Eliminate UFs from the given input formula. * * @throws InterruptedException Can be thrown by the native code. */ protected BooleanFormula applyUFEImpl(BooleanFormula pF) throws InterruptedException { return SolverUtils.ufElimination(this).eliminateUfs(pF); } /** * Eliminate quantifiers from the given input formula. * * <p>This is the light version that does not need to eliminate all quantifiers. * * @throws InterruptedException Can be thrown by the native code. */ protected BooleanFormula applyQELightImpl(BooleanFormula pF) throws InterruptedException { // Returning the untouched formula is valid according to QE_LIGHT contract. // TODO: substitution-based implementation. return pF; } /** * Apply conjunctive normal form (CNF) transformation to the given input formula. * * @param pF Input to apply the CNF transformation to. * @throws InterruptedException Can be thrown by the native code. */ protected BooleanFormula applyCNFImpl(BooleanFormula pF) throws InterruptedException { // TODO: generic implementation. throw new UnsupportedOperationException( "Currently there is no generic implementation for CNF conversion"); } /** * Apply negation normal form (NNF) transformation to the given input formula. * * @throws InterruptedException Can be thrown by the native code. */ protected BooleanFormula applyNNFImpl(BooleanFormula input) throws InterruptedException { return getBooleanFormulaManager().transformRecursively(input, new NNFVisitor(this)); } @Override public <T extends Formula> T simplify(T f) throws InterruptedException { return formulaCreator.encapsulate(formulaCreator.getFormulaType(f), simplify(extractInfo(f))); } /** * Apply a simplification procedure for the given formula. * * <p>This does not need to change something, but it might simplify the formula. * * @throws InterruptedException Can be thrown by the native code. */ protected TFormulaInfo simplify(TFormulaInfo f) throws InterruptedException { return f; } @Override public <R> R visit(Formula input, FormulaVisitor<R> visitor) { return formulaCreator.visit(input, visitor); } @Override public void visitRecursively(Formula pF, FormulaVisitor<TraversalProcess> pFormulaVisitor) { formulaCreator.visitRecursively(pFormulaVisitor, pF); } @Override public <T extends Formula> T transformRecursively( T f, FormulaTransformationVisitor pFormulaVisitor) { return formulaCreator.transformRecursively(pFormulaVisitor, f); } /** * Extract names of all free variables in a formula. * * @param f The input formula */ @Override public ImmutableMap<String, Formula> extractVariables(Formula f) { ImmutableMap.Builder<String, Formula> found = ImmutableMap.builder(); formulaCreator.extractVariablesAndUFs(f, false, found::put); return found.buildOrThrow(); // visitation should not visit any symbol twice } /** * Extract the names of all free variables and UFs in a formula. * * @param f The input formula */ @Override public ImmutableMap<String, Formula> extractVariablesAndUFs(Formula f) { ImmutableMap.Builder<String, Formula> found = ImmutableMap.builder(); formulaCreator.extractVariablesAndUFs(f, true, found::put); // We can find duplicate keys with different values, like UFs with distinct parameters. // In such a case, we use only one appearance (the last one). return found.buildKeepingLast(); } @Override public BooleanFormula translateFrom(BooleanFormula formula, FormulaManager otherManager) { if (this == otherManager) { return formula; // shortcut } return parse(otherManager.dumpFormula(formula).toString()); } @Override public <T extends Formula> T makeVariable(FormulaType<T> formulaType, String name) { checkVariableName(name); Formula t; if (formulaType.isBooleanType()) { t = booleanManager.makeVariable(name); } else if (formulaType.isIntegerType()) { assert integerManager != null; t = integerManager.makeVariable(name); } else if (formulaType.isRationalType()) { assert rationalManager != null; t = rationalManager.makeVariable(name); } else if (formulaType.isStringType()) { assert strManager != null; t = strManager.makeVariable(name); } else if (formulaType.isBitvectorType()) { assert bitvectorManager != null; t = bitvectorManager.makeVariable((BitvectorType) formulaType, name); } else if (formulaType.isFloatingPointType()) { assert floatingPointManager != null; t = floatingPointManager.makeVariable(name, (FloatingPointType) formulaType); } else if (formulaType.isArrayType()) { assert arrayManager != null; t = arrayManager.makeArray(name, (ArrayFormulaType<?, ?>) formulaType); } else { throw new IllegalArgumentException("Unknown formula type"); } @SuppressWarnings("unchecked") T out = (T) t; return out; } @Override @SuppressWarnings("unchecked") public <T extends Formula> T makeApplication( FunctionDeclaration<T> declaration, List<? extends Formula> args) { return formulaCreator.callFunction(declaration, args); } @Override public <T extends Formula> T makeApplication( FunctionDeclaration<T> declaration, Formula... args) { return makeApplication(declaration, Arrays.asList(args)); } @Override public <T extends Formula> T substitute( final T pF, final Map<? extends Formula, ? extends Formula> pFromToMapping) { return transformRecursively( pF, new FormulaTransformationVisitor(this) { @Override public Formula visitFreeVariable(Formula f, String name) { return replace(f); } @Override public Formula visitFunction( Formula f, List<Formula> newArgs, FunctionDeclaration<?> functionDeclaration) { Formula out = pFromToMapping.get(f); if (out == null) { return makeApplication(functionDeclaration, newArgs); } else { return out; } } private Formula replace(Formula f) { Formula out = pFromToMapping.get(f); if (out == null) { return f; } else { return out; } } }); } /** * Check whether the given String can be used as symbol/name for variables or undefined functions. * We disallow some keywords from SMTLib2 and other basic operators to be used as symbols. * * <p>This method must be kept in sync with {@link #checkVariableName}. */ @Override public final boolean isValidName(String pVar) { if (pVar.isEmpty()) { return false; } if (BASIC_OPERATORS.contains(pVar)) { return false; } if (SMTLIB2_KEYWORDS.contains(pVar)) { return false; } if (DISALLOWED_CHARACTERS.matchesAnyOf(pVar)) { return false; } return true; } /** * This method is similar to {@link #isValidName} and throws an exception for invalid symbol * names. While {@link #isValidName} can be used from users, this method should be used internally * to validate user-given symbol names. * * <p>This method must be kept in sync with {@link #isValidName}. */ @VisibleForTesting public static void checkVariableName(final String variableName) { final String help = "Use FormulaManager#isValidName to check your identifier before using it."; Preconditions.checkArgument( !variableName.isEmpty(), "Identifier for variable should not be empty."); Preconditions.checkArgument( !BASIC_OPERATORS.contains(variableName), "Identifier '%s' can not be used, because it is a simple operator. %s", variableName, help); Preconditions.checkArgument( !SMTLIB2_KEYWORDS.contains(variableName), "Identifier '%s' can not be used, because it is a keyword of SMT-LIB2. %s", variableName, help); Preconditions.checkArgument( DISALLOWED_CHARACTERS.matchesNoneOf(variableName), "Identifier '%s' can not be used, " + "because it should not contain an escape character %s of SMT-LIB2. %s", variableName, DISALLOWED_CHARACTER_REPLACEMENT .keySet(), // toString prints UTF8-encoded escape sequence, better than nothing. help); } /* This escaping works for simple escape sequences only, i.e., keywords are unique enough. */ @Override public final String escape(String pVar) { // as long as keywords stay simple, this simple escaping is sufficient if (pVar.isEmpty() || BASIC_OPERATORS.contains(pVar) || SMTLIB2_KEYWORDS.contains(pVar)) { return ESCAPE + pVar; } if (pVar.indexOf(ESCAPE) != -1) { pVar = pVar.replace("" + ESCAPE, "" + ESCAPE + ESCAPE); } if (DISALLOWED_CHARACTERS.matchesAnyOf(pVar)) { for (Map.Entry<Character, String> e : DISALLOWED_CHARACTER_REPLACEMENT.entrySet()) { pVar = pVar.replace(e.getKey().toString(), ESCAPE + e.getValue()); } } return pVar; // unchanged } /* This unescaping works for simple escape sequences only, i.e., keywords are unique enough. */ @Override public final String unescape(String pVar) { int idx = pVar.indexOf(ESCAPE); if (idx != -1) { // unescape BASIC_OPERATORS and SMTLIB2_KEYWORDS if (idx == 0) { String tmp = pVar.substring(1); if (tmp.isEmpty() || BASIC_OPERATORS.contains(tmp) || SMTLIB2_KEYWORDS.contains(tmp)) { return tmp; } } // unescape DISALLOWED_CHARACTERS StringBuilder str = new StringBuilder(); int i = 0; while (i < pVar.length()) { if (pVar.charAt(i) == ESCAPE) { if (pVar.charAt(i + 1) == ESCAPE) { str.append(ESCAPE); i++; } else { String rest = pVar.substring(i + 1); for (Map.Entry<Character, String> e : DISALLOWED_CHARACTER_REPLACEMENT.entrySet()) { if (rest.startsWith(e.getValue())) { str.append(e.getKey()); i += e.getValue().length(); break; } } } } else { str.append(pVar.charAt(i)); } i++; } return str.toString(); } return pVar; // unchanged } }
22,221
35.791391
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractModel.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Joiner; import org.sosy_lab.java_smt.api.Model; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractModel<TFormulaInfo, TType, TEnv> extends AbstractEvaluator<TFormulaInfo, TType, TEnv> implements Model { protected AbstractModel( AbstractProver<?> prover, FormulaCreator<TFormulaInfo, TType, TEnv, ?> creator) { super(prover, creator); } @Override public String toString() { return Joiner.on('\n').join(iterator()); } }
785
27.071429
87
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractNumeralFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkNotNull; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormulaManager; /** * Similar to the other Abstract*FormulaManager classes in this package, this class serves as a * helper for implementing {@link NumeralFormulaManager}. It handles all the unwrapping and wrapping * from {@link Formula} instances to solver-specific formula representations, such that the concrete * class needs to handle only its own internal types. * * @implSpec The method {@link #getFormulaType()} must be safe to be called from the constructor * (the default implementations of {@link org.sosy_lab.java_smt.api.IntegerFormulaManager} and * {@link org.sosy_lab.java_smt.api.RationalFormulaManager} satisfy this). */ @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractNumeralFormulaManager< TFormulaInfo, TType, TEnv, ParamFormulaType extends NumeralFormula, ResultFormulaType extends NumeralFormula, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements NumeralFormulaManager<ParamFormulaType, ResultFormulaType> { public enum NonLinearArithmetic { USE, APPROXIMATE_FALLBACK, APPROXIMATE_ALWAYS, } private final NonLinearArithmetic nonLinearArithmetic; private final TFuncDecl multUfDecl; private final TFuncDecl divUfDecl; private final TFuncDecl modUfDecl; protected AbstractNumeralFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator, NonLinearArithmetic pNonLinearArithmetic) { super(pCreator); nonLinearArithmetic = checkNotNull(pNonLinearArithmetic); multUfDecl = createBinaryFunction("*"); divUfDecl = createBinaryFunction("/"); modUfDecl = createBinaryFunction("%"); } private TFuncDecl createBinaryFunction(String name) { TType formulaType = toSolverType(getFormulaType()); return formulaCreator.declareUFImpl( getFormulaType() + "_" + name + "_", formulaType, ImmutableList.of(formulaType, formulaType)); } private TFormulaInfo makeUf(TFuncDecl decl, TFormulaInfo t1, TFormulaInfo t2) { return formulaCreator.callFunctionImpl(decl, ImmutableList.of(t1, t2)); } protected ResultFormulaType wrap(TFormulaInfo pTerm) { return getFormulaCreator().encapsulate(getFormulaType(), pTerm); } /** Check whether the argument is a numeric constant (including negated constants). */ protected abstract boolean isNumeral(TFormulaInfo val); @Override public ResultFormulaType makeNumber(long i) { return wrap(makeNumberImpl(i)); } protected abstract TFormulaInfo makeNumberImpl(long i); @Override public ResultFormulaType makeNumber(BigInteger i) { return wrap(makeNumberImpl(i)); } protected abstract TFormulaInfo makeNumberImpl(BigInteger i); @Override public ResultFormulaType makeNumber(String i) { return wrap(makeNumberImpl(i)); } protected abstract TFormulaInfo makeNumberImpl(String i); @Override public ResultFormulaType makeNumber(Rational pRational) { return wrap(makeNumberImpl(pRational)); } protected TFormulaInfo makeNumberImpl(Rational pRational) { return makeNumberImpl(pRational.toString()); } @Override public ResultFormulaType makeNumber(double pNumber) { return wrap(makeNumberImpl(pNumber)); } protected abstract TFormulaInfo makeNumberImpl(double pNumber); @Override public ResultFormulaType makeNumber(BigDecimal pNumber) { return wrap(makeNumberImpl(pNumber)); } protected abstract TFormulaInfo makeNumberImpl(BigDecimal pNumber); /** * This method tries to represent a BigDecimal using only BigInteger. It can be used for * implementing {@link #makeNumber(BigDecimal)} when the current theory supports only integers and * division by constants. */ protected final TFormulaInfo decimalAsInteger(BigDecimal val) { if (val.scale() <= 0) { // actually an integral number return makeNumberImpl(convertBigDecimalToBigInteger(val)); } else { // represent x.y by xy / (10^z) where z is the number of digits in y // (the "scale" of a BigDecimal) BigDecimal n = val.movePointRight(val.scale()); // this is "xy" BigInteger numerator = convertBigDecimalToBigInteger(n); BigDecimal d = BigDecimal.ONE.scaleByPowerOfTen(val.scale()); // this is "10^z" BigInteger denominator = convertBigDecimalToBigInteger(d); assert denominator.signum() > 0; return divide(makeNumberImpl(numerator), makeNumberImpl(denominator)); } } private static BigInteger convertBigDecimalToBigInteger(BigDecimal d) throws NumberFormatException { try { return d.toBigIntegerExact(); } catch (ArithmeticException e) { NumberFormatException nfe = new NumberFormatException("Cannot represent BigDecimal " + d + " as BigInteger"); nfe.initCause(e); throw nfe; } } @Override public ResultFormulaType makeVariable(String pVar) { checkVariableName(pVar); return wrap(makeVariableImpl(pVar)); } protected abstract TFormulaInfo makeVariableImpl(String i); @Override public ResultFormulaType negate(ParamFormulaType pNumber) { TFormulaInfo param1 = extractInfo(pNumber); return wrap(negate(param1)); } protected abstract TFormulaInfo negate(TFormulaInfo pParam1); @Override public ResultFormulaType add(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(add(param1, param2)); } protected abstract TFormulaInfo add(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public ResultFormulaType sum(List<ParamFormulaType> operands) { return wrap(sumImpl(Lists.transform(operands, this::extractInfo))); } protected TFormulaInfo sumImpl(List<TFormulaInfo> operands) { TFormulaInfo result = makeNumberImpl(0); for (TFormulaInfo operand : operands) { result = add(result, operand); } return result; } @Override public ResultFormulaType subtract(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrap(subtract(param1, param2)); } protected abstract TFormulaInfo subtract(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public ResultFormulaType divide(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); TFormulaInfo result; // division is always non-linear for ints, and for rationals if param2 is not a constant: // http://smtlib.cs.uiowa.edu/logics-all.shtml#LIA // http://smtlib.cs.uiowa.edu/logics-all.shtml#LRA if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_ALWAYS && (getFormulaType().equals(FormulaType.IntegerType) || !isNumeral(param2))) { result = makeUf(divUfDecl, param1, param2); } else { try { result = divide(param1, param2); } catch (UnsupportedOperationException e) { if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK) { result = makeUf(divUfDecl, param1, param2); } else { assert nonLinearArithmetic == NonLinearArithmetic.USE; throw e; } } } return wrap(result); } /** * If a solver does not support this operation, e.g. because of missing support for non-linear * arithmetics, we throw UnsupportedOperationException. * * @param pParam1 the dividend * @param pParam2 the divisor */ protected TFormulaInfo divide(TFormulaInfo pParam1, TFormulaInfo pParam2) { throw new UnsupportedOperationException(); } public ResultFormulaType modulo(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); TFormulaInfo result; if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_ALWAYS) { result = makeUf(modUfDecl, param1, param2); } else { try { result = modulo(param1, param2); } catch (UnsupportedOperationException e) { if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK) { result = makeUf(modUfDecl, param1, param2); } else { assert nonLinearArithmetic == NonLinearArithmetic.USE; throw e; } } } return wrap(result); } /** * If a solver does not support this operation, e.g. because of missing support for non-linear * arithmetics, we throw UnsupportedOperationException. * * @param pParam1 the dividend * @param pParam2 the divisor */ protected TFormulaInfo modulo(TFormulaInfo pParam1, TFormulaInfo pParam2) { throw new UnsupportedOperationException(); } public BooleanFormula modularCongruence( ParamFormulaType pNumber1, ParamFormulaType pNumber2, long pModulo) { Preconditions.checkArgument(pModulo > 0, "modular congruence needs a positive modulo."); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(modularCongruence(param1, param2, pModulo)); } public BooleanFormula modularCongruence( ParamFormulaType pNumber1, ParamFormulaType pNumber2, BigInteger pModulo) { Preconditions.checkArgument( pModulo.signum() > 0, "modular congruence needs a positive modulo."); TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(modularCongruence(param1, param2, pModulo)); } /** * @param a first operand * @param b second operand * @param m the modulus * @return the formula representing {@code a = b (mod m)} */ protected TFormulaInfo modularCongruence(TFormulaInfo a, TFormulaInfo b, BigInteger m) { throw new UnsupportedOperationException(); } /** * @param a first operand * @param b second operand * @param m the modulus * @return the formula representing {@code a = b (mod m)} */ protected TFormulaInfo modularCongruence(TFormulaInfo a, TFormulaInfo b, long m) { throw new UnsupportedOperationException(); } @Override public ResultFormulaType multiply(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); TFormulaInfo result; if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_ALWAYS && !isNumeral(param1) && !isNumeral(param2)) { result = makeUf(multUfDecl, param1, param2); } else { try { result = multiply(param1, param2); } catch (UnsupportedOperationException e) { if (nonLinearArithmetic == NonLinearArithmetic.APPROXIMATE_FALLBACK) { result = makeUf(multUfDecl, param1, param2); } else { assert nonLinearArithmetic == NonLinearArithmetic.USE : "unexpected handling of nonlinear arithmetics: " + nonLinearArithmetic; throw e; } } } return wrap(result); } /** * If a solver does not support this operation, e.g. because of missing support for non-linear * arithmetics, we throw UnsupportedOperationException. * * @param pParam1 first factor * @param pParam2 second factor */ protected TFormulaInfo multiply(TFormulaInfo pParam1, TFormulaInfo pParam2) { throw new UnsupportedOperationException(); } @Override public BooleanFormula equal(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(equal(param1, param2)); } protected abstract TFormulaInfo equal(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula distinct(List<ParamFormulaType> pNumbers) { return wrapBool(distinctImpl(Lists.transform(pNumbers, this::extractInfo))); } protected abstract TFormulaInfo distinctImpl(List<TFormulaInfo> pNumbers); @Override public BooleanFormula greaterThan(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterThan(param1, param2)); } protected abstract TFormulaInfo greaterThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterOrEquals(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(greaterOrEquals(param1, param2)); } protected abstract TFormulaInfo greaterOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessThan(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessThan(param1, param2)); } protected abstract TFormulaInfo lessThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessOrEquals(ParamFormulaType pNumber1, ParamFormulaType pNumber2) { TFormulaInfo param1 = extractInfo(pNumber1); TFormulaInfo param2 = extractInfo(pNumber2); return wrapBool(lessOrEquals(param1, param2)); } protected abstract TFormulaInfo lessOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public IntegerFormula floor(ParamFormulaType number) { if (getFormulaCreator().getFormulaType(number) == FormulaType.IntegerType) { return (IntegerFormula) number; } else { return getFormulaCreator().encapsulate(FormulaType.IntegerType, floor(extractInfo(number))); } } protected TFormulaInfo floor(TFormulaInfo number) { // identity function for integers, method is overridden for rationals throw new AssertionError( "method should only be called for RationalFormulae, but type is " + getFormulaCreator().getFormulaType(number)); } }
15,105
33.488584
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractProver.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import java.util.LinkedHashSet; import java.util.Set; import org.sosy_lab.java_smt.api.BasicProverEnvironment; import org.sosy_lab.java_smt.api.Evaluator; import org.sosy_lab.java_smt.api.SolverContext.ProverOptions; public abstract class AbstractProver<T> implements BasicProverEnvironment<T> { private final boolean generateModels; private final boolean generateAllSat; protected final boolean generateUnsatCores; private final boolean generateUnsatCoresOverAssumptions; protected final boolean enableSL; private final Set<Evaluator> evaluators = new LinkedHashSet<>(); private static final String TEMPLATE = "Please set the prover option %s."; protected AbstractProver(Set<ProverOptions> pOptions) { generateModels = pOptions.contains(ProverOptions.GENERATE_MODELS); generateAllSat = pOptions.contains(ProverOptions.GENERATE_ALL_SAT); generateUnsatCores = pOptions.contains(ProverOptions.GENERATE_UNSAT_CORE); generateUnsatCoresOverAssumptions = pOptions.contains(ProverOptions.GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS); enableSL = pOptions.contains(ProverOptions.ENABLE_SEPARATION_LOGIC); } protected final void checkGenerateModels() { Preconditions.checkState(generateModels, TEMPLATE, ProverOptions.GENERATE_MODELS); } protected final void checkGenerateAllSat() { Preconditions.checkState(generateAllSat, TEMPLATE, ProverOptions.GENERATE_ALL_SAT); } protected final void checkGenerateUnsatCores() { Preconditions.checkState(generateUnsatCores, TEMPLATE, ProverOptions.GENERATE_UNSAT_CORE); } protected final void checkGenerateUnsatCoresOverAssumptions() { Preconditions.checkState( generateUnsatCoresOverAssumptions, TEMPLATE, ProverOptions.GENERATE_UNSAT_CORE_OVER_ASSUMPTIONS); } protected final void checkEnableSeparationLogic() { Preconditions.checkState(enableSL, TEMPLATE, ProverOptions.ENABLE_SEPARATION_LOGIC); } /** * This method registers the Evaluator to be cleaned up before the next change on the prover * stack. */ protected <E extends Evaluator> E registerEvaluator(E pEvaluator) { evaluators.add(pEvaluator); return pEvaluator; } protected void unregisterEvaluator(Evaluator pEvaluator) { evaluators.remove(pEvaluator); } protected void closeAllEvaluators() { evaluators.forEach(Evaluator::close); evaluators.clear(); } @Override public void close() { closeAllEvaluators(); } }
2,800
31.952941
94
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractProverWithAllSat.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Set; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Evaluator; import org.sosy_lab.java_smt.api.SolverContext.ProverOptions; import org.sosy_lab.java_smt.api.SolverException; /** * This class is a utility-class to avoid repeated implementation of the AllSAT computation. * * <p>If a solver does not support direct AllSAT computation, please inherit from this class. */ public abstract class AbstractProverWithAllSat<T> extends AbstractProver<T> { protected final ShutdownNotifier shutdownNotifier; private final BooleanFormulaManager bmgr; protected boolean closed; protected AbstractProverWithAllSat( Set<ProverOptions> pOptions, BooleanFormulaManager pBmgr, ShutdownNotifier pShutdownNotifier) { super(pOptions); bmgr = pBmgr; shutdownNotifier = pShutdownNotifier; } @Override public <R> R allSat(AllSatCallback<R> callback, List<BooleanFormula> importantPredicates) throws InterruptedException, SolverException { Preconditions.checkState(!closed); checkGenerateAllSat(); push(); try { // try model-based computation of ALLSAT iterateOverAllModels(callback, importantPredicates); } catch (SolverException e) { // fallback to direct SAT/UNSAT-based computation of ALLSAT iterateOverAllPredicateCombinations(callback, importantPredicates, new ArrayDeque<>()); // TODO should we completely switch to the second method? } pop(); return callback.getResult(); } /** * This method computes all satisfiable assignments for the given predicates by iterating over all * models. The SMT solver can choose the ordering of variables and shortcut model generation. */ private <R> void iterateOverAllModels( AllSatCallback<R> callback, List<BooleanFormula> importantPredicates) throws SolverException, InterruptedException { while (!isUnsat()) { shutdownNotifier.shutdownIfNecessary(); ImmutableList.Builder<BooleanFormula> valuesOfModel = ImmutableList.builder(); try (Evaluator evaluator = getEvaluatorWithoutChecks()) { for (BooleanFormula formula : importantPredicates) { Boolean value = evaluator.evaluate(formula); if (value == null) { // This is a legal return value for evaluation. // The value doesn't matter. We ignore this assignment. // This step aim for shortcutting the ALLSAT-loop. } else if (value) { valuesOfModel.add(formula); } else { valuesOfModel.add(bmgr.not(formula)); } } } final ImmutableList<BooleanFormula> values = valuesOfModel.build(); callback.apply(values); shutdownNotifier.shutdownIfNecessary(); BooleanFormula negatedModel = bmgr.not(bmgr.and(values)); addConstraint(negatedModel); shutdownNotifier.shutdownIfNecessary(); } } /** * This method computes all satisfiable assignments for the given predicates by (recursively) * traversing the decision tree over the given variables. The ordering of variables is fixed, and * we can only ignore unsatisfiable subtrees. * * <p>In contrast to {@link #iterateOverAllModels} we do not use model generation here, which is a * benefit for some solvers or theory combinations. * * @param predicates remaining predicates in the decision tree. * @param valuesOfModel already chosen predicate values, ordered as appearing in the tree. */ private <R> void iterateOverAllPredicateCombinations( AllSatCallback<R> callback, List<BooleanFormula> predicates, Deque<BooleanFormula> valuesOfModel) throws SolverException, InterruptedException { shutdownNotifier.shutdownIfNecessary(); if (isUnsat()) { return; } else if (predicates.isEmpty()) { // we aim at providing the same order of predicates as given as parameter, thus reverse. callback.apply(ImmutableList.copyOf(valuesOfModel).reverse()); } else { // positive predicate final BooleanFormula predicate = predicates.get(0); valuesOfModel.push(predicate); push(predicate); iterateOverAllPredicateCombinations( callback, predicates.subList(1, predicates.size()), valuesOfModel); pop(); valuesOfModel.pop(); // negated predicate final BooleanFormula notPredicate = bmgr.not(predicates.get(0)); valuesOfModel.push(notPredicate); push(notPredicate); iterateOverAllPredicateCombinations( callback, predicates.subList(1, predicates.size()), valuesOfModel); pop(); valuesOfModel.pop(); } } /** * Get an evaluator instance for model evaluation without executing checks for prover options. * * <p>This method allows model evaluation without explicitly enabling the prover-option {@link * ProverOptions#GENERATE_MODELS}. We only use this method internally, when we know about a valid * solver state. The returned evaluator does not have caching or any direct optimization for user * interaction. * * @throws SolverException if model can not be constructed. */ protected abstract Evaluator getEvaluatorWithoutChecks() throws SolverException; }
5,833
35.236025
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractQuantifiedFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.collect.Lists; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager; import org.sosy_lab.java_smt.api.SolverException; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractQuantifiedFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements QuantifiedFormulaManager { protected AbstractQuantifiedFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator) { super(pCreator); } private BooleanFormula wrap(TFormulaInfo formulaInfo) { return getFormulaCreator().encapsulateBoolean(formulaInfo); } @Override public BooleanFormula eliminateQuantifiers(BooleanFormula pF) throws InterruptedException, SolverException { return wrap(eliminateQuantifiers(extractInfo(pF))); } protected abstract TFormulaInfo eliminateQuantifiers(TFormulaInfo pExtractInfo) throws SolverException, InterruptedException; @Override public BooleanFormula mkQuantifier( Quantifier q, List<? extends Formula> pVariables, BooleanFormula pBody) { return wrap( mkQuantifier(q, Lists.transform(pVariables, this::extractInfo), extractInfo(pBody))); } public abstract TFormulaInfo mkQuantifier( Quantifier q, List<TFormulaInfo> vars, TFormulaInfo body); }
1,756
33.45098
93
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractSLFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.SLFormulaManager; @SuppressWarnings({"ClassTypeParameterName", "MethodTypeParameterName"}) public abstract class AbstractSLFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements SLFormulaManager { protected AbstractSLFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator) { super(pCreator); } private BooleanFormula wrap(TFormulaInfo pTerm) { return getFormulaCreator().encapsulateBoolean(pTerm); } @Override public BooleanFormula makeStar(BooleanFormula f1, BooleanFormula f2) { TFormulaInfo param1 = extractInfo(f1); TFormulaInfo param2 = extractInfo(f2); return wrap(makeStar(param1, param2)); } protected abstract TFormulaInfo makeStar(TFormulaInfo e1, TFormulaInfo e2); @Override public BooleanFormula makePointsTo(Formula ptr, Formula to) { TFormulaInfo param1 = extractInfo(ptr); TFormulaInfo param2 = extractInfo(to); return wrap(makePointsTo(param1, param2)); } protected abstract TFormulaInfo makePointsTo(TFormulaInfo ptr, TFormulaInfo to); @Override public BooleanFormula makeMagicWand(BooleanFormula f1, BooleanFormula f2) { TFormulaInfo param1 = extractInfo(f1); TFormulaInfo param2 = extractInfo(f2); return wrap(makeMagicWand(param1, param2)); } protected abstract TFormulaInfo makeMagicWand(TFormulaInfo e1, TFormulaInfo e2); @Override public < AF extends Formula, VF extends Formula, AT extends FormulaType<AF>, VT extends FormulaType<VF>> BooleanFormula makeEmptyHeap(AT pAdressType, VT pValueType) { final TType adressType = toSolverType(pAdressType); final TType valueType = toSolverType(pValueType); return wrap(makeEmptyHeap(adressType, valueType)); } protected abstract TFormulaInfo makeEmptyHeap(TType e1, TType e2); @Override public <AF extends Formula, AT extends FormulaType<AF>> AF makeNilElement(AT pAdressType) { final TType type = toSolverType(pAdressType); return getFormulaCreator().encapsulate(pAdressType, makeNilElement(type)); } protected abstract TFormulaInfo makeNilElement(TType type); }
2,672
32.835443
93
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractSolverContext.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.OptimizationProverEnvironment; import org.sosy_lab.java_smt.api.ProverEnvironment; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper.InterpolatingProverWithAssumptionsWrapper; import org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper.ProverWithAssumptionsWrapper; public abstract class AbstractSolverContext implements SolverContext { private final FormulaManager fmgr; protected AbstractSolverContext(FormulaManager fmgr) { this.fmgr = fmgr; } @Override public final FormulaManager getFormulaManager() { return fmgr; } @Override public final ProverEnvironment newProverEnvironment(ProverOptions... options) { ProverEnvironment out = newProverEnvironment0(toSet(options)); if (!supportsAssumptionSolving()) { // In the case we do not already have a prover environment with assumptions, // we add a wrapper to it out = new ProverWithAssumptionsWrapper(out); } return out; } protected abstract ProverEnvironment newProverEnvironment0(Set<ProverOptions> options); @SuppressWarnings("resource") @Override public final InterpolatingProverEnvironment<?> newProverEnvironmentWithInterpolation( ProverOptions... options) { InterpolatingProverEnvironment<?> out = newProverEnvironmentWithInterpolation0(toSet(options)); if (!supportsAssumptionSolving()) { // In the case we do not already have a prover environment with assumptions, // we add a wrapper to it out = new InterpolatingProverWithAssumptionsWrapper<>(out, fmgr); } return out; } protected abstract InterpolatingProverEnvironment<?> newProverEnvironmentWithInterpolation0( Set<ProverOptions> pSet); @SuppressWarnings("resource") @Override public final OptimizationProverEnvironment newOptimizationProverEnvironment( ProverOptions... options) { return newOptimizationProverEnvironment0(toSet(options)); } protected abstract OptimizationProverEnvironment newOptimizationProverEnvironment0( Set<ProverOptions> pSet); /** * Whether the solver supports solving under some given assumptions (with all corresponding * features) by itself, i.e., whether {@link * ProverEnvironment#isUnsatWithAssumptions(java.util.Collection)} and {@link * InterpolatingProverEnvironment#isUnsatWithAssumptions(java.util.Collection)} are fully * implemented. * * <p>Otherwise, i.e., if this method returns {@code false}, the solver does not need to support * this feature and may simply {@code throw UnsupportedOperationException} in the respective * methods. This class will wrap the prover environments and provide an implementation of the * feature. * * <p>This method is expected to always return the same value. Otherwise, the behavior of this * class is undefined. */ protected abstract boolean supportsAssumptionSolving(); private static Set<ProverOptions> toSet(ProverOptions... options) { Set<ProverOptions> opts = EnumSet.noneOf(ProverOptions.class); Collections.addAll(opts, options); return opts; } /** * This method loads the given libraries. * * <p>If the first list of libraries can not be loaded, the second list is used as a fallback. The * two lists of libraries can be used to differ between libraries specific to Unix/Linux and * Windows. * * <p>If the first try aborts after a few steps, we do not clean up partially loaded libraries, * but directly start the second try. * * <p>Each list is applied in the given ordering. * * @param loader the loading mechanism that will be used for loading each single library. * @param librariesForFirstTry list of library names that will be loaded, if possible. * @param librariesForSecondTry list of library names that will be loaded, after the first attempt * (using librariesForFirstTry) has failed. * @throws UnsatisfiedLinkError if neither the first nor second try returned a successful loading * process. */ protected static void loadLibrariesWithFallback( Consumer<String> loader, List<String> librariesForFirstTry, List<String> librariesForSecondTry) throws UnsatisfiedLinkError { Preconditions.checkNotNull(librariesForFirstTry); Preconditions.checkNotNull(librariesForSecondTry); try { librariesForFirstTry.forEach(loader); } catch (UnsatisfiedLinkError e1) { try { librariesForSecondTry.forEach(loader); } catch (UnsatisfiedLinkError e2) { e1.addSuppressed(e2); throw e1; } } } }
5,232
36.647482
104
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractStringFormulaManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Alejandro SerranoMena // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.StringFormula; import org.sosy_lab.java_smt.api.StringFormulaManager; @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractStringFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFuncDecl> implements StringFormulaManager { protected AbstractStringFormulaManager( FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> pCreator) { super(pCreator); } private StringFormula wrapString(TFormulaInfo formulaInfo) { return getFormulaCreator().encapsulateString(formulaInfo); } private RegexFormula wrapRegex(TFormulaInfo formulaInfo) { return getFormulaCreator().encapsulateRegex(formulaInfo); } @Override public StringFormula makeString(String value) { return wrapString(makeStringImpl(value)); } protected abstract TFormulaInfo makeStringImpl(String value); @Override public StringFormula makeVariable(String pVar) { checkVariableName(pVar); return wrapString(makeVariableImpl(pVar)); } protected abstract TFormulaInfo makeVariableImpl(String pVar); @Override public BooleanFormula equal(StringFormula str1, StringFormula str2) { return wrapBool(equal(extractInfo(str1), extractInfo(str2))); } protected abstract TFormulaInfo equal(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterThan(StringFormula str1, StringFormula str2) { return wrapBool(greaterThan(extractInfo(str1), extractInfo(str2))); } protected abstract TFormulaInfo greaterThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula greaterOrEquals(StringFormula str1, StringFormula str2) { return wrapBool(greaterOrEquals(extractInfo(str1), extractInfo(str2))); } protected abstract TFormulaInfo greaterOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessThan(StringFormula str1, StringFormula str2) { return wrapBool(lessThan(extractInfo(str1), extractInfo(str2))); } protected abstract TFormulaInfo lessThan(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public BooleanFormula lessOrEquals(StringFormula str1, StringFormula str2) { return wrapBool(lessOrEquals(extractInfo(str1), extractInfo(str2))); } protected abstract TFormulaInfo lessOrEquals(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public NumeralFormula.IntegerFormula length(StringFormula str) { return getFormulaCreator().encapsulate(FormulaType.IntegerType, length(extractInfo(str))); } protected abstract TFormulaInfo length(TFormulaInfo pParam); @Override public StringFormula concat(List<StringFormula> parts) { switch (parts.size()) { case 0: return makeString(""); // empty sequence case 1: return Iterables.getOnlyElement(parts); default: return wrapString(concatImpl(Lists.transform(parts, this::extractInfo))); } } protected abstract TFormulaInfo concatImpl(List<TFormulaInfo> parts); @Override public BooleanFormula prefix(StringFormula prefix, StringFormula str) { return wrapBool(prefix(extractInfo(prefix), extractInfo(str))); } protected abstract TFormulaInfo prefix(TFormulaInfo prefix, TFormulaInfo str); @Override public BooleanFormula suffix(StringFormula suffix, StringFormula str) { return wrapBool(suffix(extractInfo(suffix), extractInfo(str))); } protected abstract TFormulaInfo suffix(TFormulaInfo suffix, TFormulaInfo str); @Override public BooleanFormula in(StringFormula str, RegexFormula regex) { return wrapBool(in(extractInfo(str), extractInfo(regex))); } protected abstract TFormulaInfo in(TFormulaInfo str, TFormulaInfo regex); @Override public BooleanFormula contains(StringFormula str, StringFormula part) { return wrapBool(contains(extractInfo(str), extractInfo(part))); } protected abstract TFormulaInfo contains(TFormulaInfo str, TFormulaInfo part); @Override public IntegerFormula indexOf(StringFormula str, StringFormula part, IntegerFormula startIndex) { return getFormulaCreator() .encapsulate( FormulaType.IntegerType, indexOf(extractInfo(str), extractInfo(part), extractInfo(startIndex))); } protected abstract TFormulaInfo indexOf( TFormulaInfo str, TFormulaInfo part, TFormulaInfo startIndex); @Override public StringFormula charAt(StringFormula str, IntegerFormula index) { return wrapString(charAt(extractInfo(str), extractInfo(index))); } protected abstract TFormulaInfo charAt(TFormulaInfo str, TFormulaInfo index); @Override public StringFormula substring(StringFormula str, IntegerFormula index, IntegerFormula length) { return wrapString(substring(extractInfo(str), extractInfo(index), extractInfo(length))); } protected abstract TFormulaInfo substring( TFormulaInfo str, TFormulaInfo index, TFormulaInfo length); @Override public StringFormula replace( StringFormula fullStr, StringFormula target, StringFormula replacement) { return wrapString(replace(extractInfo(fullStr), extractInfo(target), extractInfo(replacement))); } protected abstract TFormulaInfo replace( TFormulaInfo fullStr, TFormulaInfo target, TFormulaInfo replacement); @Override public StringFormula replaceAll( StringFormula fullStr, StringFormula target, StringFormula replacement) { return wrapString( replaceAll(extractInfo(fullStr), extractInfo(target), extractInfo(replacement))); } protected abstract TFormulaInfo replaceAll( TFormulaInfo fullStr, TFormulaInfo target, TFormulaInfo replacement); @Override public RegexFormula makeRegex(String value) { return wrapRegex(makeRegexImpl(value)); } protected abstract TFormulaInfo makeRegexImpl(String value); @Override public RegexFormula none() { return wrapRegex(noneImpl()); } protected abstract TFormulaInfo noneImpl(); @Override public RegexFormula all() { return wrapRegex(allImpl()); } protected abstract TFormulaInfo allImpl(); @Override public RegexFormula allChar() { return wrapRegex(allCharImpl()); } protected abstract TFormulaInfo allCharImpl(); @Override public RegexFormula range(StringFormula start, StringFormula end) { return wrapRegex(range(extractInfo(start), extractInfo(end))); } protected abstract TFormulaInfo range(TFormulaInfo start, TFormulaInfo end); @Override public RegexFormula concatRegex(List<RegexFormula> parts) { switch (parts.size()) { case 0: return none(); // empty sequence case 1: return Iterables.getOnlyElement(parts); default: return wrapRegex(concatRegexImpl(Lists.transform(parts, this::extractInfo))); } } protected abstract TFormulaInfo concatRegexImpl(List<TFormulaInfo> parts); @Override public RegexFormula union(RegexFormula regex1, RegexFormula regex2) { return wrapRegex(union(extractInfo(regex1), extractInfo(regex2))); } protected abstract TFormulaInfo union(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public RegexFormula intersection(RegexFormula regex1, RegexFormula regex2) { return wrapRegex(intersection(extractInfo(regex1), extractInfo(regex2))); } protected abstract TFormulaInfo intersection(TFormulaInfo pParam1, TFormulaInfo pParam2); @Override public RegexFormula closure(RegexFormula regex) { return wrapRegex(closure(extractInfo(regex))); } protected abstract TFormulaInfo closure(TFormulaInfo pParam); @Override public RegexFormula complement(RegexFormula regex) { return wrapRegex(complement(extractInfo(regex))); } protected abstract TFormulaInfo complement(TFormulaInfo pParam); @Override public RegexFormula difference(RegexFormula regex1, RegexFormula regex2) { return wrapRegex(difference(extractInfo(regex1), extractInfo(regex2))); } protected TFormulaInfo difference(TFormulaInfo pParam1, TFormulaInfo pParam2) { return intersection(pParam1, complement(pParam2)); } @Override public RegexFormula cross(RegexFormula regex) { return concat(regex, closure(regex)); } @Override public RegexFormula optional(RegexFormula regex) { return union(regex, makeRegex("")); } @Override public RegexFormula times(RegexFormula regex, int repetitions) { return concatRegex(Collections.nCopies(repetitions, regex)); } @Override public IntegerFormula toIntegerFormula(StringFormula str) { return getFormulaCreator() .encapsulate(FormulaType.IntegerType, toIntegerFormula(extractInfo(str))); } protected abstract TFormulaInfo toIntegerFormula(TFormulaInfo pParam); @Override public StringFormula toStringFormula(IntegerFormula number) { return wrapString(toStringFormula(extractInfo(number))); } protected abstract TFormulaInfo toStringFormula(TFormulaInfo pParam); }
9,712
31.056106
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/AbstractUFManager.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager.checkVariableName; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.UFManager; /** * This class simplifies the implementation of the FunctionFormulaManager by converting the types to * the solver specific type. * * @param <TFormulaInfo> The solver specific type. * @param <TFunctionDecl> The solver specific type of declarations of any function application * @param <TType> The solver specific type of formula-types. */ @SuppressWarnings("ClassTypeParameterName") public abstract class AbstractUFManager<TFormulaInfo, TFunctionDecl, TType, TEnv> extends AbstractBaseFormulaManager<TFormulaInfo, TType, TEnv, TFunctionDecl> implements UFManager { protected AbstractUFManager(FormulaCreator<TFormulaInfo, TType, TEnv, TFunctionDecl> pCreator) { super(pCreator); } @Override public final <T extends Formula> FunctionDeclaration<T> declareUF( String pName, FormulaType<T> pReturnType, List<FormulaType<?>> pArgTypes) { checkVariableName(pName); List<TType> argTypes = Lists.transform(pArgTypes, this::toSolverType); return FunctionDeclarationImpl.of( pName, FunctionDeclarationKind.UF, pArgTypes, pReturnType, formulaCreator.declareUFImpl(pName, toSolverType(pReturnType), argTypes)); } @Override public <T extends Formula> FunctionDeclaration<T> declareUF( String pName, FormulaType<T> pReturnType, FormulaType<?>... pArgs) { checkVariableName(pName); return declareUF(pName, pReturnType, Arrays.asList(pArgs)); } @Override public <T extends Formula> T callUF(FunctionDeclaration<T> funcType, Formula... args) { return formulaCreator.callFunction(funcType, Arrays.asList(args)); } @Override public final <T extends Formula> T callUF( FunctionDeclaration<T> pFunc, List<? extends Formula> pArgs) { return formulaCreator.callFunction(pFunc, pArgs); } @Override public <T extends Formula> T declareAndCallUF( String name, FormulaType<T> pReturnType, List<Formula> pArgs) { checkVariableName(name); List<FormulaType<?>> argTypes = Lists.transform(pArgs, getFormulaCreator()::getFormulaType); FunctionDeclaration<T> func = declareUF(name, pReturnType, argTypes); return callUF(func, pArgs); } @Override public <T extends Formula> T declareAndCallUF( String name, FormulaType<T> pReturnType, Formula... pArgs) { checkVariableName(name); return declareAndCallUF(name, pReturnType, Arrays.asList(pArgs)); } }
3,111
35.186047
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/CachingModel.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.math.BigInteger; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.Model; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; import org.sosy_lab.java_smt.api.StringFormula; public class CachingModel implements Model { private final Model delegate; private @Nullable ImmutableList<ValueAssignment> modelAssignments = null; public CachingModel(Model pDelegate) { delegate = Preconditions.checkNotNull(pDelegate); } @Override public ImmutableList<ValueAssignment> asList() { if (modelAssignments == null) { modelAssignments = delegate.asList(); } return modelAssignments; } @Override public void close() { delegate.close(); } @Override public <T extends Formula> @Nullable T eval(T formula) { return delegate.eval(formula); } @Override public @Nullable Object evaluate(Formula formula) { return delegate.evaluate(formula); } @Override public @Nullable BigInteger evaluate(IntegerFormula formula) { return delegate.evaluate(formula); } @Override public @Nullable Rational evaluate(RationalFormula formula) { return delegate.evaluate(formula); } @Override public @Nullable Boolean evaluate(BooleanFormula formula) { return delegate.evaluate(formula); } @Override public @Nullable BigInteger evaluate(BitvectorFormula formula) { return delegate.evaluate(formula); } @Override public @Nullable String evaluate(StringFormula formula) { return delegate.evaluate(formula); } @Override public @Nullable String evaluate(EnumerationFormula formula) { return delegate.evaluate(formula); } }
2,367
25.909091
75
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/FormulaCreator.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Predicate; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.EnumerationFormula; import org.sosy_lab.java_smt.api.FloatingPointFormula; import org.sosy_lab.java_smt.api.FloatingPointRoundingModeFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType; import org.sosy_lab.java_smt.api.FormulaType.FloatingPointType; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.RegexFormula; import org.sosy_lab.java_smt.api.StringFormula; import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.ArrayFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.BitvectorFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.BooleanFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.EnumerationFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.FloatingPointFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.FloatingPointRoundingModeFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.IntegerFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.RationalFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.RegexFormulaImpl; import org.sosy_lab.java_smt.basicimpl.AbstractFormula.StringFormulaImpl; /** * This is a helper class with several methods that are commonly used throughout the basicimpl * package and may have solver-specific implementations. Each solver package is expected to provide * an instance of this class, with the appropriate methods overwritten. Depending on the solver, * some or all non-final methods in this class may need to be overwritten. * * @param <TFormulaInfo> the solver specific type for formulas. * @param <TType> the solver specific type for formula types. * @param <TEnv> the solver specific type for the environment/context. */ @SuppressWarnings({"ClassTypeParameterName", "MethodTypeParameterName"}) public abstract class FormulaCreator<TFormulaInfo, TType, TEnv, TFuncDecl> { private final TType boolType; private final @Nullable TType integerType; private final @Nullable TType rationalType; private final @Nullable TType stringType; private final @Nullable TType regexType; protected final TEnv environment; protected FormulaCreator( TEnv env, TType boolType, @Nullable TType pIntegerType, @Nullable TType pRationalType, @Nullable TType stringType, @Nullable TType regexType) { this.environment = env; this.boolType = boolType; this.integerType = pIntegerType; this.rationalType = pRationalType; this.stringType = stringType; this.regexType = regexType; } public final TEnv getEnv() { return environment; } public final TType getBoolType() { return boolType; } public final TType getIntegerType() { if (integerType == null) { throw new UnsupportedOperationException("Integer theory is not supported by this solver."); } return integerType; } public final TType getRationalType() { if (rationalType == null) { throw new UnsupportedOperationException("Rational theory is not supported by this solver."); } return rationalType; } public abstract TType getBitvectorType(int bitwidth); public abstract TType getFloatingPointType(FloatingPointType type); public abstract TType getArrayType(TType indexType, TType elementType); public final TType getStringType() { if (stringType == null) { throw new UnsupportedOperationException("String theory is not supported by this solver."); } return stringType; } public final TType getRegexType() { if (regexType == null) { throw new UnsupportedOperationException("String theory is not supported by this solver."); } return regexType; } public abstract TFormulaInfo makeVariable(TType type, String varName); public BooleanFormula encapsulateBoolean(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isBooleanType(); return new BooleanFormulaImpl<>(pTerm); } protected BitvectorFormula encapsulateBitvector(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isBitvectorType(); return new BitvectorFormulaImpl<>(pTerm); } protected FloatingPointFormula encapsulateFloatingPoint(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isFloatingPointType(); return new FloatingPointFormulaImpl<>(pTerm); } protected <TI extends Formula, TE extends Formula> ArrayFormula<TI, TE> encapsulateArray( TFormulaInfo pTerm, FormulaType<TI> pIndexType, FormulaType<TE> pElementType) { assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType)) : "Expected: " + getFormulaType(pTerm) + " but found: " + FormulaType.getArrayType(pIndexType, pElementType); return new ArrayFormulaImpl<>(pTerm, pIndexType, pElementType); } protected StringFormula encapsulateString(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isStringType(); return new StringFormulaImpl<>(pTerm); } protected RegexFormula encapsulateRegex(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isRegexType(); return new RegexFormulaImpl<>(pTerm); } protected EnumerationFormula encapsulateEnumeration(TFormulaInfo pTerm) { assert getFormulaType(pTerm).isEnumerationType(); return new EnumerationFormulaImpl<>(pTerm); } public Formula encapsulateWithTypeOf(TFormulaInfo pTerm) { return encapsulate(getFormulaType(pTerm), pTerm); } @SuppressWarnings("unchecked") public <T extends Formula> T encapsulate(FormulaType<T> pType, TFormulaInfo pTerm) { assert pType.equals(getFormulaType(pTerm)) : String.format( "Trying to encapsulate formula %s of type %s as %s", pTerm, getFormulaType(pTerm), pType); if (pType.isBooleanType()) { return (T) new BooleanFormulaImpl<>(pTerm); } else if (pType.isIntegerType()) { return (T) new IntegerFormulaImpl<>(pTerm); } else if (pType.isRationalType()) { return (T) new RationalFormulaImpl<>(pTerm); } else if (pType.isStringType()) { return (T) new StringFormulaImpl<>(pTerm); } else if (pType.isRegexType()) { return (T) new RegexFormulaImpl<>(pTerm); } else if (pType.isBitvectorType()) { return (T) new BitvectorFormulaImpl<>(pTerm); } else if (pType.isFloatingPointType()) { return (T) new FloatingPointFormulaImpl<>(pTerm); } else if (pType.isFloatingPointRoundingModeType()) { return (T) new FloatingPointRoundingModeFormulaImpl<>(pTerm); } else if (pType.isArrayType()) { ArrayFormulaType<?, ?> arrayType = (ArrayFormulaType<?, ?>) pType; return (T) encapsulateArray(pTerm, arrayType.getIndexType(), arrayType.getElementType()); } else if (pType.isEnumerationType()) { return (T) new EnumerationFormulaImpl<>(pTerm); } throw new IllegalArgumentException( "Cannot create formulas of type " + pType + " in the Solver!"); } @SuppressWarnings("unchecked") protected TFormulaInfo extractInfo(Formula pT) { if (pT instanceof AbstractFormula) { return ((AbstractFormula<TFormulaInfo>) pT).getFormulaInfo(); } throw new IllegalArgumentException( "Cannot get the formula info of type " + pT.getClass().getSimpleName() + " in the Solver!"); } @SuppressWarnings("unchecked") protected <TI extends Formula, TE extends Formula> FormulaType<TE> getArrayFormulaElementType( ArrayFormula<TI, TE> pArray) { return ((ArrayFormulaImpl<TI, TE, TFormulaInfo>) pArray).getElementType(); } @SuppressWarnings("unchecked") protected <TI extends Formula, TE extends Formula> FormulaType<TI> getArrayFormulaIndexType( ArrayFormula<TI, TE> pArray) { return ((ArrayFormulaImpl<TI, TE, TFormulaInfo>) pArray).getIndexType(); } /** Returns the type of the given Formula. */ @SuppressWarnings("unchecked") protected <T extends Formula> FormulaType<T> getFormulaType(T formula) { checkNotNull(formula); FormulaType<?> t; if (formula instanceof BooleanFormula) { t = FormulaType.BooleanType; } else if (formula instanceof IntegerFormula) { t = FormulaType.IntegerType; } else if (formula instanceof RationalFormula) { t = FormulaType.RationalType; } else if (formula instanceof StringFormula) { t = FormulaType.StringType; } else if (formula instanceof RegexFormula) { t = FormulaType.RegexType; } else if (formula instanceof FloatingPointRoundingModeFormula) { t = FormulaType.FloatingPointRoundingModeType; } else if (formula instanceof ArrayFormula) { throw new UnsupportedOperationException( "SMT solvers with support for arrays need to overwrite FormulaCreator.getFormulaType()"); } else if (formula instanceof BitvectorFormula) { throw new UnsupportedOperationException( "SMT solvers with support for bitvectors " + "need to overwrite FormulaCreator.getFormulaType()"); } else if (formula instanceof EnumerationFormula) { throw new UnsupportedOperationException( "SMT solvers with support for enumerations need to overwrite FormulaCreator" + ".getFormulaType()"); } else { throw new IllegalArgumentException("Formula with unexpected type " + formula.getClass()); } return (FormulaType<T>) t; } public abstract FormulaType<?> getFormulaType(TFormulaInfo formula); /** * @see org.sosy_lab.java_smt.api.FormulaManager#visit */ @CanIgnoreReturnValue public <R> R visit(Formula input, FormulaVisitor<R> visitor) { return visit(visitor, input, extractInfo(input)); } /** * @see org.sosy_lab.java_smt.api.FormulaManager#visit */ public abstract <R> R visit(FormulaVisitor<R> visitor, Formula formula, TFormulaInfo f); protected List<TFormulaInfo> extractInfo(List<? extends Formula> input) { return Lists.transform(input, this::extractInfo); } /** * @see org.sosy_lab.java_smt.api.FormulaManager#visitRecursively */ public void visitRecursively(FormulaVisitor<TraversalProcess> pFormulaVisitor, Formula pF) { visitRecursively(pFormulaVisitor, pF, t -> true); } /** * @see org.sosy_lab.java_smt.api.FormulaManager#visitRecursively */ public void visitRecursively( FormulaVisitor<TraversalProcess> pFormulaVisitor, Formula pF, Predicate<Formula> shouldProcess) { RecursiveFormulaVisitorImpl recVisitor = new RecursiveFormulaVisitorImpl(pFormulaVisitor); recVisitor.addToQueue(pF); while (!recVisitor.isQueueEmpty()) { Formula tt = recVisitor.pop(); if (shouldProcess.test(tt)) { TraversalProcess process = visit(tt, recVisitor); if (process == TraversalProcess.ABORT) { return; } } } } public <T extends Formula> T transformRecursively( FormulaVisitor<? extends Formula> pFormulaVisitor, T pF) { return transformRecursively(pFormulaVisitor, pF, t -> true); } public <T extends Formula> T transformRecursively( FormulaVisitor<? extends Formula> pFormulaVisitor, T pF, Predicate<Object> shouldProcess) { final Deque<Formula> toProcess = new ArrayDeque<>(); Map<Formula, Formula> pCache = new HashMap<>(); FormulaTransformationVisitorImpl recVisitor = new FormulaTransformationVisitorImpl(pFormulaVisitor, toProcess, pCache); toProcess.push(pF); // Process the work queue while (!toProcess.isEmpty()) { Formula tt = toProcess.peek(); if (pCache.containsKey(tt)) { toProcess.pop(); continue; } if (shouldProcess.test(tt)) { visit(tt, recVisitor); } else { pCache.put(tt, tt); } } @SuppressWarnings("unchecked") T out = (T) pCache.get(pF); return out; } /** * Wrapper for {@link #extractVariablesAndUFs(Formula, boolean, BiConsumer)} which unwraps both * input and output. */ public Map<String, TFormulaInfo> extractVariablesAndUFs( final TFormulaInfo pFormula, final boolean extractUFs) { Map<String, TFormulaInfo> found = new LinkedHashMap<>(); extractVariablesAndUFs( encapsulateWithTypeOf(pFormula), extractUFs, (name, f) -> found.put(name, extractInfo(f))); return found; } /** * Wrapper for {@link #extractVariablesAndUFs(Formula, boolean, BiConsumer)} which unwraps both * input and output. */ public void extractVariablesAndUFs( final TFormulaInfo pFormula, final boolean extractUFs, final BiConsumer<String, TFormulaInfo> pConsumer) { extractVariablesAndUFs( encapsulateWithTypeOf(pFormula), extractUFs, (name, f) -> pConsumer.accept(name, extractInfo(f))); } /** Extract all free variables from the formula, optionally including UFs. */ public void extractVariablesAndUFs( final Formula pFormula, final boolean extractUF, final BiConsumer<String, Formula> pConsumer) { visitRecursively( new VariableAndUFExtractor(extractUF, pConsumer, ImmutableSet.of(), new LinkedHashSet<>()), pFormula); } private class VariableAndUFExtractor extends DefaultFormulaVisitor<TraversalProcess> { private final boolean extractUF; private final BiConsumer<String, Formula> consumer; private final Set<Formula> boundVariablesInContext; /** * let's collect all visited symbols here, to avoid redundant visitation of symbols in nested * quantified formulas. */ private final Set<Formula> alreadyVisited; VariableAndUFExtractor( boolean pExtractUF, BiConsumer<String, Formula> pConsumer, Set<Formula> pBoundVariablesInContext, Set<Formula> pAlreadyVisited) { extractUF = pExtractUF; consumer = pConsumer; boundVariablesInContext = pBoundVariablesInContext; alreadyVisited = pAlreadyVisited; } @Override protected TraversalProcess visitDefault(Formula f) { return TraversalProcess.CONTINUE; } @Override public TraversalProcess visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { if (!boundVariablesInContext.contains(f) // TODO can UFs be bounded? && functionDeclaration.getKind() == FunctionDeclarationKind.UF && extractUF) { if (alreadyVisited.add(f)) { consumer.accept(functionDeclaration.getName(), f); } } return TraversalProcess.CONTINUE; } @Override public TraversalProcess visitFreeVariable(Formula f, String name) { // If we are inside a quantified formula, bound variables appear to be free, // but they are actually bound by the surrounding context. if (!boundVariablesInContext.contains(f)) { if (alreadyVisited.add(f)) { consumer.accept(name, f); } } return TraversalProcess.CONTINUE; } @Override public TraversalProcess visitQuantifier( BooleanFormula f, Quantifier q, List<Formula> boundVariables, BooleanFormula body) { // We begin a new nested scope, thus we need a 'really' recursive call and // use another visitor-instance which knows the corresponding bound variables. visitRecursively( new VariableAndUFExtractor( extractUF, consumer, Sets.union(boundVariablesInContext, ImmutableSet.copyOf(boundVariables)), alreadyVisited), body); // Afterwards, we skip the already finished body-formula. return TraversalProcess.SKIP; } } @SuppressWarnings("unchecked") public final <T extends Formula> T callFunction( FunctionDeclaration<T> declaration, List<? extends Formula> args) { checkArgument( args.size() >= declaration.getArgumentTypes().size(), "function application '%s' requires %s arguments, but received %s arguments", declaration, declaration.getArgumentTypes().size(), args.size()); for (int i = 0; i < args.size(); i++) { // For chainable functions like EQ, DISTINCT, ADD, LESS, LESS_EQUAL, ..., with a variable // number of arguments, we repeat the last argument-type several times. int index = Math.min(i, declaration.getArgumentTypes().size() - 1); checkArgument( isCompatible(getFormulaType(args.get(i)), declaration.getArgumentTypes().get(index)), "function application '%s' requires argument types %s, but received argument types %s", declaration, declaration.getArgumentTypes(), Lists.transform(args, this::getFormulaType)); } return encapsulate( declaration.getType(), callFunctionImpl( ((FunctionDeclarationImpl<T, TFuncDecl>) declaration).getSolverDeclaration(), extractInfo(args))); } /** * This function checks whether the used type of the function argument is compatible with the * declared type in the function declaration. * * <p>Identical types are always compatible, a subtype like INT to supertype RATIONAL is also * compatible. A solver-specific wrapper can override this method if it does an explicit * transformation between (some) types, e.g., from BV to BOOLEAN or from BOOLEAN to INT. */ protected boolean isCompatible(FormulaType<?> usedType, FormulaType<?> declaredType) { // INT is a subtype of RATIONAL if (usedType.isIntegerType() && declaredType.isRationalType()) { return true; } return usedType.equals(declaredType); } public abstract TFormulaInfo callFunctionImpl(TFuncDecl declaration, List<TFormulaInfo> args); public abstract TFuncDecl declareUFImpl(String pName, TType pReturnType, List<TType> pArgTypes); public TFuncDecl getBooleanVarDeclaration(BooleanFormula var) { return getBooleanVarDeclarationImpl(extractInfo(var)); } protected abstract TFuncDecl getBooleanVarDeclarationImpl(TFormulaInfo pTFormulaInfo); /** * Convert the formula into a Java object as far as possible, i.e., try to match a primitive or * simple type like Boolean, BigInteger, Rational, or String. * * <p>If the formula is not a simple constant expression, we simply return <code>null</code>. * * @param pF the formula to be converted. */ public Object convertValue(TFormulaInfo pF) { throw new UnsupportedOperationException( "This SMT solver needs a second term to determine a correct type. " + "Please use the other method 'convertValue(formula, formula)'."); } /** * Convert the formula into a Java object as far as possible, i.e., try to match a primitive or * simple type. * * @param pAdditionalF an additional formula where the type can be received from. * @param pF the formula to be converted. */ // only some solvers require the additional (first) parameter, other solvers ignore it. public Object convertValue( @SuppressWarnings("unused") TFormulaInfo pAdditionalF, TFormulaInfo pF) { return convertValue(pF); } /** Variable names (symbols) can be wrapped with "|". This function removes those chars. */ protected static String dequote(String s) { int l = s.length(); if (s.charAt(0) == '|' && s.charAt(l - 1) == '|') { return s.substring(1, l - 1); } return s; } }
20,958
36.900542
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/FormulaTransformationVisitorImpl.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.Map; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; /** Internal implementation of recursive transformation. */ final class FormulaTransformationVisitorImpl implements FormulaVisitor<Void> { private final Deque<Formula> toProcess; private final Map<Formula, Formula> pCache; private final FormulaVisitor<? extends Formula> delegate; FormulaTransformationVisitorImpl( FormulaVisitor<? extends Formula> delegate, Deque<Formula> toProcess, Map<Formula, Formula> pCache) { this.toProcess = Preconditions.checkNotNull(toProcess); this.pCache = Preconditions.checkNotNull(pCache); this.delegate = Preconditions.checkNotNull(delegate); } @Override public Void visitFreeVariable(Formula f, String name) { pCache.put(f, delegate.visitFreeVariable(f, name)); return null; } @Override public Void visitBoundVariable(Formula f, int deBruijnIdx) { Preconditions.checkNotNull(f); // Bound variable transformation is not allowed. pCache.put(f, f); return null; } @Override public Void visitConstant(Formula f, Object value) { Preconditions.checkNotNull(f); pCache.put(f, delegate.visitConstant(f, value)); return null; } @Override public Void visitFunction( Formula f, List<Formula> args, FunctionDeclaration<?> functionDeclaration) { Preconditions.checkNotNull(f); boolean allArgumentsTransformed = true; // Construct a new argument list for the function application. List<Formula> newArgs = new ArrayList<>(args.size()); for (Formula c : args) { Formula newC = pCache.get(c); if (newC != null) { newArgs.add(newC); } else { toProcess.push(c); allArgumentsTransformed = false; } } // The Flag childrenDone indicates whether all arguments // of the function were already processed. if (allArgumentsTransformed) { // Create a processed version of the function application. if (!toProcess.isEmpty()) { toProcess.pop(); } Formula out = delegate.visitFunction(f, newArgs, functionDeclaration); Formula prev = pCache.put(f, out); assert prev == null; } return null; } @Override public Void visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula body) { Preconditions.checkNotNull(f); Preconditions.checkNotNull(quantifier); Preconditions.checkNotNull(boundVariables); Preconditions.checkNotNull(body); BooleanFormula transformedBody = (BooleanFormula) pCache.get(body); if (transformedBody != null) { BooleanFormula newTt = (BooleanFormula) delegate.visitQuantifier(f, quantifier, boundVariables, transformedBody); pCache.put(f, newTt); } else { toProcess.push(body); } return null; } }
3,496
28.888889
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/FunctionDeclarationImpl.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2022 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; import java.util.List; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; /** Declaration of a function. */ @Immutable(containerOf = "T") @AutoValue public abstract class FunctionDeclarationImpl<F extends Formula, T> implements FunctionDeclaration<F> { public static <F extends Formula, T> FunctionDeclaration<F> of( String name, FunctionDeclarationKind kind, List<FormulaType<?>> pArgumentTypes, FormulaType<F> pReturnType, T pDeclaration) { return new AutoValue_FunctionDeclarationImpl<>( kind, name, pReturnType, ImmutableList.copyOf(pArgumentTypes), pDeclaration); } /** * get a reference to the internal declaration used by the SMT solver. This method should only be * used internally in JavaSMT. */ public abstract T getSolverDeclaration(); @Override public final String toString() { return String.format("%s (%s)", getKind(), getName()); } }
1,497
30.87234
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/PackageSanityTest.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.testing.AbstractPackageSanityTests; import org.sosy_lab.common.ShutdownManager; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.java_smt.api.FormulaType; public class PackageSanityTest extends AbstractPackageSanityTests { { setDistinctValues(FormulaType.class, FormulaType.BooleanType, FormulaType.IntegerType); setDefault(ShutdownNotifier.class, ShutdownManager.create().getNotifier()); } }
730
30.782609
91
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/RecursiveFormulaVisitorImpl.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.visitors.FormulaVisitor; import org.sosy_lab.java_smt.api.visitors.TraversalProcess; import org.sosy_lab.java_smt.api.visitors.TraversalProcess.TraversalType; final class RecursiveFormulaVisitorImpl implements FormulaVisitor<TraversalProcess> { private final Set<Formula> seen = new HashSet<>(); private final Deque<Formula> toVisit = new ArrayDeque<>(); private final FormulaVisitor<TraversalProcess> delegate; RecursiveFormulaVisitorImpl(FormulaVisitor<TraversalProcess> pDelegate) { delegate = checkNotNull(pDelegate); } void addToQueue(Formula f) { if (seen.add(f)) { toVisit.push(f); } } boolean isQueueEmpty() { return toVisit.isEmpty(); } private void addToQueueIfNecessary(TraversalProcess result, List<? extends Formula> pOperands) { if (result == TraversalProcess.CONTINUE) { for (Formula f : pOperands) { addToQueue(f); } } else if (result.getType() == TraversalType.CUSTOM_TYPE) { pOperands.stream().filter(result::contains).forEach(this::addToQueue); } } Formula pop() { return toVisit.pop(); } @Override public TraversalProcess visitFreeVariable(Formula pF, String pName) { return delegate.visitFreeVariable(pF, pName); } @Override public TraversalProcess visitBoundVariable(Formula pF, int pDeBruijnIdx) { return delegate.visitBoundVariable(pF, pDeBruijnIdx); } @Override public TraversalProcess visitConstant(Formula pF, Object pValue) { return delegate.visitConstant(pF, pValue); } @Override public TraversalProcess visitFunction( Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) { TraversalProcess result = delegate.visitFunction(pF, pArgs, pFunctionDeclaration); addToQueueIfNecessary(result, pArgs); return result; } @Override public TraversalProcess visitQuantifier( BooleanFormula pF, Quantifier pQuantifier, List<Formula> boundVars, BooleanFormula pBody) { TraversalProcess result = delegate.visitQuantifier(pF, pQuantifier, boundVars, pBody); addToQueueIfNecessary(result, ImmutableList.of(pBody)); return result; } }
2,920
30.408602
98
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/ShutdownHook.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2021 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl; import com.google.common.base.Preconditions; import java.util.concurrent.atomic.AtomicBoolean; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.ShutdownNotifier; import org.sosy_lab.common.ShutdownNotifier.ShutdownRequestListener; /** * A utility class for interrupting a parallel running solver thread. * * <p>The hook is active directly after its construction until calling the method {@link * ShutdownHook#close()} and forwards all shutdown requests to the provided method. */ public final class ShutdownHook implements ShutdownRequestListener, AutoCloseable { private final ShutdownNotifier shutdownNotifier; private final Runnable interruptCall; public ShutdownHook(ShutdownNotifier pShutdownNotifier, Runnable pInterruptCall) { interruptCall = Preconditions.checkNotNull(pInterruptCall); shutdownNotifier = Preconditions.checkNotNull(pShutdownNotifier); shutdownNotifier.register(this); } final AtomicBoolean isActiveHook = new AtomicBoolean(true); // Due to a small delay in some solvers, interrupts have no effect when it is called too soon, // so we repeat cancellation until the solver's method returns and terminates. // In that case, we should call #close and terminate this hook. @Override public void shutdownRequested(@Nullable String reasonUnused) { while (isActiveHook.get()) { // flag is reset in #cancelHook interruptCall.run(); try { Thread.sleep(10); // let's wait a few steps } catch (InterruptedException e) { // ignore } } } @Override public void close() { isActiveHook.set(false); shutdownNotifier.unregister(this); } }
1,972
33.614035
96
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** Abstract base classes for easier implementation of a solver backend. */ @com.google.errorprone.annotations.CheckReturnValue @javax.annotation.ParametersAreNonnullByDefault @org.sosy_lab.common.annotations.FieldsAreNonnullByDefault @org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault package org.sosy_lab.java_smt.basicimpl;
581
37.8
75
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/tactics/NNFVisitor.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl.tactics; import com.google.common.collect.Lists; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor; public class NNFVisitor extends BooleanFormulaTransformationVisitor { private final NNFInsideNotVisitor insideNotVisitor; private final BooleanFormulaManager bfmgr; public NNFVisitor(FormulaManager pFmgr) { super(pFmgr); bfmgr = pFmgr.getBooleanFormulaManager(); insideNotVisitor = new NNFInsideNotVisitor(pFmgr); } @Override public BooleanFormula visitNot(BooleanFormula processedOperand) { return bfmgr.visit(processedOperand, insideNotVisitor); } @Override public BooleanFormula visitXor( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.visit(rewriteXor(processedOperand1, processedOperand2), this); } private BooleanFormula rewriteXor(BooleanFormula operand1, BooleanFormula operand2) { return bfmgr.or( bfmgr.and(operand1, bfmgr.not(operand2)), bfmgr.and(bfmgr.not(operand1), operand2)); } @Override public BooleanFormula visitEquivalence( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.visit(rewriteEquivalence(processedOperand1, processedOperand2), this); } private BooleanFormula rewriteEquivalence(BooleanFormula pOperand1, BooleanFormula pOperand2) { return bfmgr.or( bfmgr.and(pOperand1, pOperand2), bfmgr.and(bfmgr.not(pOperand1), bfmgr.not(pOperand2))); } @Override public BooleanFormula visitImplication( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.visit(rewriteImplication(processedOperand1, processedOperand2), this); } private BooleanFormula rewriteImplication(BooleanFormula pOperand1, BooleanFormula pOperand2) { return bfmgr.or(bfmgr.not(pOperand1), pOperand2); } @Override public BooleanFormula visitIfThenElse( BooleanFormula processedCondition, BooleanFormula processedThenFormula, BooleanFormula processedElseFormula) { return bfmgr.visit( rewriteIfThenElse(processedCondition, processedThenFormula, processedElseFormula), this); } private BooleanFormula rewriteIfThenElse( BooleanFormula pCondition, BooleanFormula pThenFormula, BooleanFormula pElseFormula) { return bfmgr.or( bfmgr.and(pCondition, pThenFormula), bfmgr.and(bfmgr.not(pCondition), pElseFormula)); } private class NNFInsideNotVisitor extends BooleanFormulaTransformationVisitor { protected NNFInsideNotVisitor(FormulaManager pFmgr) { super(pFmgr); } @Override public BooleanFormula visitConstant(boolean value) { return bfmgr.makeBoolean(value); } @Override public BooleanFormula visitAtom( BooleanFormula pAtom, FunctionDeclaration<BooleanFormula> decl) { return bfmgr.not(pAtom); } @Override public BooleanFormula visitNot(BooleanFormula processedOperand) { return bfmgr.visit(processedOperand, NNFVisitor.this); } @Override public BooleanFormula visitAnd(List<BooleanFormula> processedOperands) { return bfmgr.or(Lists.transform(processedOperands, f -> bfmgr.visit(f, this))); } @Override public BooleanFormula visitOr(List<BooleanFormula> processedOperands) { return bfmgr.and(Lists.transform(processedOperands, f -> bfmgr.visit(f, this))); } @Override public BooleanFormula visitXor( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.visit(rewriteXor(processedOperand1, processedOperand2), this); } @Override public BooleanFormula visitEquivalence( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { return bfmgr.visit(rewriteEquivalence(processedOperand1, processedOperand2), this); } @Override public BooleanFormula visitImplication( BooleanFormula processedOperand1, BooleanFormula processedOperand2) { // Rewrite using primitives. return bfmgr.visit(bfmgr.or(bfmgr.not(processedOperand1), processedOperand2), this); } @Override public BooleanFormula visitIfThenElse( BooleanFormula processedCondition, BooleanFormula processedThenFormula, BooleanFormula processedElseFormula) { return bfmgr.visit( rewriteIfThenElse(processedCondition, processedThenFormula, processedElseFormula), this); } } }
4,946
33.594406
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/tactics/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** Default tactics implementations (formula-to-formula transformations). */ package org.sosy_lab.java_smt.basicimpl.tactics;
366
32.363636
76
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/withAssumptionsWrapper/BasicProverWithAssumptionsWrapper.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import org.sosy_lab.java_smt.api.BasicProverEnvironment; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Model; import org.sosy_lab.java_smt.api.SolverException; public class BasicProverWithAssumptionsWrapper<T, P extends BasicProverEnvironment<T>> implements BasicProverEnvironment<T> { protected final P delegate; protected final List<BooleanFormula> solverAssumptionsAsFormula = new ArrayList<>(); BasicProverWithAssumptionsWrapper(P pDelegate) { delegate = pDelegate; } protected void clearAssumptions() { for (int i = 0; i < solverAssumptionsAsFormula.size(); i++) { delegate.pop(); } solverAssumptionsAsFormula.clear(); } @Override public void pop() { clearAssumptions(); delegate.pop(); } @Override public T addConstraint(BooleanFormula constraint) throws InterruptedException { clearAssumptions(); return delegate.addConstraint(constraint); } @Override public void push() throws InterruptedException { clearAssumptions(); delegate.push(); } @Override public int size() { return delegate.size(); } @Override public boolean isUnsat() throws SolverException, InterruptedException { clearAssumptions(); return delegate.isUnsat(); } @Override public boolean isUnsatWithAssumptions(Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException { clearAssumptions(); solverAssumptionsAsFormula.addAll(assumptions); for (BooleanFormula formula : assumptions) { registerPushedFormula(delegate.push(formula)); } return delegate.isUnsat(); } /** overridden in sub-class. */ protected void registerPushedFormula(@SuppressWarnings("unused") T pPushResult) {} @Override public Model getModel() throws SolverException { return delegate.getModel(); } @Override public ImmutableList<Model.ValueAssignment> getModelAssignments() throws SolverException { return delegate.getModelAssignments(); } @Override public List<BooleanFormula> getUnsatCore() { return delegate.getUnsatCore(); } @Override public Optional<List<BooleanFormula>> unsatCoreOverAssumptions( Collection<BooleanFormula> pAssumptions) throws SolverException, InterruptedException { clearAssumptions(); return delegate.unsatCoreOverAssumptions(pAssumptions); // if (isUnsatWithAssumptions(pAssumptions)) { // // TODO project to pAssumptions? // return Optional.of(getUnsatCore()); // } else { // return Optional.empty(); // } } @Override public ImmutableMap<String, String> getStatistics() { return delegate.getStatistics(); } @Override public void close() { delegate.close(); } @Override public <R> R allSat(AllSatCallback<R> pCallback, List<BooleanFormula> pImportant) throws InterruptedException, SolverException { clearAssumptions(); return delegate.allSat(pCallback, pImportant); } }
3,508
26.629921
93
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/withAssumptionsWrapper/InterpolatingProverWithAssumptionsWrapper.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FunctionDeclaration; import org.sosy_lab.java_smt.api.FunctionDeclarationKind; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.visitors.BooleanFormulaTransformationVisitor; public class InterpolatingProverWithAssumptionsWrapper<T> extends BasicProverWithAssumptionsWrapper<T, InterpolatingProverEnvironment<T>> implements InterpolatingProverEnvironment<T> { private final List<T> solverAssumptionsFromPush; private final FormulaManager fmgr; private final BooleanFormulaManager bmgr; public InterpolatingProverWithAssumptionsWrapper( InterpolatingProverEnvironment<T> pDelegate, FormulaManager pFmgr) { super(pDelegate); solverAssumptionsFromPush = new ArrayList<>(); fmgr = checkNotNull(pFmgr); bmgr = fmgr.getBooleanFormulaManager(); } @Override public BooleanFormula getInterpolant(Collection<T> pFormulasOfA) throws SolverException, InterruptedException { List<T> completeListOfA = new ArrayList<>(pFormulasOfA); completeListOfA.addAll(solverAssumptionsFromPush); BooleanFormula interpolant = delegate.getInterpolant(completeListOfA); // remove assumption variables from the rawInterpolant if necessary if (!solverAssumptionsAsFormula.isEmpty()) { interpolant = bmgr.transformRecursively(interpolant, new RemoveAssumptionsFromFormulaVisitor()); } return interpolant; } @Override public List<BooleanFormula> getSeqInterpolants(List<? extends Collection<T>> pPartitionedFormulas) throws SolverException, InterruptedException { if (solverAssumptionsAsFormula.isEmpty()) { return delegate.getSeqInterpolants(pPartitionedFormulas); } else { throw new UnsupportedOperationException(); } } @Override public List<BooleanFormula> getTreeInterpolants( List<? extends Collection<T>> pPartitionedFormulas, int[] pStartOfSubTree) throws SolverException, InterruptedException { if (solverAssumptionsAsFormula.isEmpty()) { return delegate.getTreeInterpolants(pPartitionedFormulas, pStartOfSubTree); } else { throw new UnsupportedOperationException(); } } @Override protected void registerPushedFormula(T pPushResult) { solverAssumptionsFromPush.add(pPushResult); } @Override protected void clearAssumptions() { super.clearAssumptions(); solverAssumptionsFromPush.clear(); } class RemoveAssumptionsFromFormulaVisitor extends BooleanFormulaTransformationVisitor { private RemoveAssumptionsFromFormulaVisitor() { super(fmgr); } @Override public BooleanFormula visitAtom(BooleanFormula atom, FunctionDeclaration<BooleanFormula> decl) { if (decl.getKind() == FunctionDeclarationKind.VAR) { String varName = decl.getName(); // TODO is it sound to replace a variable with TRUE? if (solverAssumptionsContainsVar(varName)) { return bmgr.makeBoolean(true); } else { return bmgr.makeVariable(varName); } } else { return atom; } } private boolean solverAssumptionsContainsVar(String variableName) { for (BooleanFormula solverVar : solverAssumptionsAsFormula) { if (fmgr.extractVariables(solverVar).containsKey(variableName)) { return true; } } return false; } } }
4,059
32.833333
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/withAssumptionsWrapper/ProverWithAssumptionsWrapper.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper; import org.sosy_lab.java_smt.api.ProverEnvironment; public class ProverWithAssumptionsWrapper extends BasicProverWithAssumptionsWrapper<Void, ProverEnvironment> implements ProverEnvironment { public ProverWithAssumptionsWrapper(ProverEnvironment pDelegate) { super(pDelegate); } }
604
27.809524
70
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/basicimpl/withAssumptionsWrapper/package-info.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 /** * Wrapper-classes to guarantee identical behavior for all solvers. If a solver does not support * {@link org.sosy_lab.java_smt.api.BasicProverEnvironment#isUnsatWithAssumptions}, we wrap it in a * (subclass of) BasicProverWithAssumptionsWrapper, whose task it is to keep the assumptions as long * on the solver's stack as no other operation accesses it. It allows computing interpolants and * unsat cores. without direct support from the solver. */ package org.sosy_lab.java_smt.basicimpl.withAssumptionsWrapper;
763
43.941176
100
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/delegate/logging/LoggingBasicProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.delegate.logging; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.logging.Level; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.api.BasicProverEnvironment; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Model; import org.sosy_lab.java_smt.api.Model.ValueAssignment; import org.sosy_lab.java_smt.api.SolverException; /** Wraps a basic prover environment with a logging object. */ class LoggingBasicProverEnvironment<T> implements BasicProverEnvironment<T> { private final BasicProverEnvironment<T> wrapped; final LogManager logger; private int level = 0; LoggingBasicProverEnvironment(BasicProverEnvironment<T> pWrapped, LogManager pLogger) { wrapped = checkNotNull(pWrapped); logger = checkNotNull(pLogger); } @Override public T push(BooleanFormula f) throws InterruptedException { logger.log(Level.FINE, "up to level " + level++); logger.log(Level.FINE, "formula pushed:", f); return wrapped.push(f); } @Override public void pop() { logger.log(Level.FINER, "down to level " + level--); wrapped.pop(); } @Override public T addConstraint(BooleanFormula constraint) throws InterruptedException { return wrapped.addConstraint(constraint); } @Override public void push() throws InterruptedException { logger.log(Level.FINE, "up to level " + level++); wrapped.push(); } @Override public int size() { int result = wrapped.size(); Preconditions.checkState(result == level); logger.log(Level.FINE, "number of levels " + result); return result; } @Override public boolean isUnsat() throws SolverException, InterruptedException { boolean result = wrapped.isUnsat(); logger.log(Level.FINE, "unsat-check returned:", result); return result; } @Override public boolean isUnsatWithAssumptions(Collection<BooleanFormula> pAssumptions) throws SolverException, InterruptedException { logger.log(Level.FINE, "assumptions:", pAssumptions); boolean result = wrapped.isUnsatWithAssumptions(pAssumptions); logger.log(Level.FINE, "unsat-check returned:", result); return result; } @Override public Model getModel() throws SolverException { Model m = wrapped.getModel(); logger.log(Level.FINE, "model", m); return m; } @Override public ImmutableList<ValueAssignment> getModelAssignments() throws SolverException { ImmutableList<ValueAssignment> m = wrapped.getModelAssignments(); logger.log(Level.FINE, "model", m); return m; } @Override public List<BooleanFormula> getUnsatCore() { List<BooleanFormula> unsatCore = wrapped.getUnsatCore(); logger.log(Level.FINE, "unsat-core", unsatCore); return unsatCore; } @Override public Optional<List<BooleanFormula>> unsatCoreOverAssumptions( Collection<BooleanFormula> assumptions) throws SolverException, InterruptedException { Optional<List<BooleanFormula>> result = wrapped.unsatCoreOverAssumptions(assumptions); logger.log(Level.FINE, "unsat-check returned:", result.isEmpty()); return result; } @Override public ImmutableMap<String, String> getStatistics() { return wrapped.getStatistics(); } @Override public void close() { wrapped.close(); logger.log(Level.FINER, "closed"); } @Override public <R> R allSat(AllSatCallback<R> callback, List<BooleanFormula> important) throws InterruptedException, SolverException { R result = wrapped.allSat(callback, important); logger.log(Level.FINE, "allsat-result:", result); return result; } }
4,125
29.338235
92
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/delegate/logging/LoggingInterpolatingProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.delegate.logging; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; import java.util.List; import java.util.logging.Level; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.SolverException; class LoggingInterpolatingProverEnvironment<T> extends LoggingBasicProverEnvironment<T> implements InterpolatingProverEnvironment<T> { private final InterpolatingProverEnvironment<T> wrapped; LoggingInterpolatingProverEnvironment(LogManager logger, InterpolatingProverEnvironment<T> ipe) { super(ipe, logger); this.wrapped = checkNotNull(ipe); } @Override public BooleanFormula getInterpolant(Collection<T> formulasOfA) throws SolverException, InterruptedException { logger.log(Level.FINE, "formulasOfA:", formulasOfA); BooleanFormula bf = wrapped.getInterpolant(formulasOfA); logger.log(Level.FINE, "interpolant:", bf); return bf; } @Override public List<BooleanFormula> getSeqInterpolants(List<? extends Collection<T>> partitionedFormulas) throws SolverException, InterruptedException { logger.log(Level.FINE, "formulasOfA:", partitionedFormulas); List<BooleanFormula> bf = wrapped.getSeqInterpolants(partitionedFormulas); logger.log(Level.FINE, "interpolants:", bf); return bf; } @Override public List<BooleanFormula> getTreeInterpolants( List<? extends Collection<T>> partitionedFormulas, int[] startOfSubTree) throws SolverException, InterruptedException { logger.log(Level.FINE, "formulasOfA:", partitionedFormulas); logger.log(Level.FINE, "startOfSubTree:", startOfSubTree); List<BooleanFormula> bf = wrapped.getTreeInterpolants(partitionedFormulas, startOfSubTree); logger.log(Level.FINE, "interpolants:", bf); return bf; } }
2,198
35.65
99
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/delegate/logging/LoggingOptimizationProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.delegate.logging; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Optional; import java.util.logging.Level; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.common.rationals.Rational; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.OptimizationProverEnvironment; import org.sosy_lab.java_smt.api.SolverException; /** Wrapper for an optimizing solver. */ class LoggingOptimizationProverEnvironment extends LoggingBasicProverEnvironment<Void> implements OptimizationProverEnvironment { private final OptimizationProverEnvironment wrapped; LoggingOptimizationProverEnvironment(LogManager logger, OptimizationProverEnvironment oe) { super(oe, logger); this.wrapped = checkNotNull(oe); } @Override public int maximize(Formula objective) { logger.log(Level.FINE, "Maximizing:", objective); return wrapped.maximize(objective); } @Override public int minimize(Formula objective) { logger.log(Level.FINE, "Minimizing:", objective); return wrapped.minimize(objective); } @Override public OptStatus check() throws InterruptedException, SolverException { OptStatus result = wrapped.check(); logger.log(Level.FINE, "optimization returned", result); return result; } @Override public Optional<Rational> upper(int handle, Rational epsilon) { return wrapped.upper(handle, epsilon); } @Override public Optional<Rational> lower(int handle, Rational epsilon) { return wrapped.lower(handle, epsilon); } }
1,824
28.918033
93
java
java-smt
java-smt-master/src/org/sosy_lab/java_smt/delegate/logging/LoggingProverEnvironment.java
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: // https://github.com/sosy-lab/java-smt // // SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.java_smt.delegate.logging; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.java_smt.api.ProverEnvironment; /** Wraps a prover environment with a logging object. */ class LoggingProverEnvironment extends LoggingBasicProverEnvironment<Void> implements ProverEnvironment { LoggingProverEnvironment(LogManager logger, ProverEnvironment pe) { super(pe, logger); } }
652
28.681818
74
java