diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4a7e620b9c7816fb6caefdaa9e1122dc3b3a6955..5b63889538d9e6a53e741ee0a351373b73bae993 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,4 @@ -image: openjdk:8-jdk-slim +image: eclipse-temurin:8 stages: - test @@ -6,14 +6,14 @@ stages: variables: GRADLE_OPTIONS: --no-daemon --info --stacktrace --warning-mode=all + GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle" cache: paths: - - .gradle/wrapper - .gradle/caches - -before_script: - - export GRADLE_USER_HOME=`pwd`/.gradle + - .gradle/native + - .gradle/notifications + - .gradle/wrapper tests: stage: test @@ -21,18 +21,22 @@ tests: tests:jdk-11: extends: tests - image: openjdk:11-jdk-slim + image: eclipse-temurin:11 tests:jdk-17: extends: tests - image: openjdk:17-jdk-slim + image: eclipse-temurin:17 + +tests:jdk-21: + extends: tests + image: eclipse-temurin:21 publish: stage: deploy script: - - openssl aes-256-cbc -pass "env:ENCRYPTION_PASSWORD" -d -a -md md5 -in secring.gpg.enc -out secring.gpg - - openssl aes-256-cbc -pass "env:ENCRYPTION_PASSWORD" -d -a -md md5 -in pubring.gpg.enc -out pubring.gpg - - openssl aes-256-cbc -pass "env:ENCRYPTION_PASSWORD" -d -a -md md5 -in gradle.properties.enc -out gradle.properties + - openssl aes-256-cbc -d -base64 -pbkdf2 -pass "env:ENCRYPTION_PASSWORD" -in gradle.properties.enc -out gradle.properties + - openssl aes-256-cbc -d -base64 -pbkdf2 -pass "env:ENCRYPTION_PASSWORD" -in pubring.gpg.enc -out pubring.gpg + - openssl aes-256-cbc -d -base64 -pbkdf2 -pass "env:ENCRYPTION_PASSWORD" -in secring.gpg.enc -out secring.gpg - ./gradlew ${GRADLE_OPTIONS} publish only: - master@general/stups/tlc4b diff --git a/README.md b/README.md index ece10b6dd1a3daba5f17a83840f2267b4ef6aa5e..6883009a471d4284092f8bf060bfde50e3b5a97f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,17 @@ TLC4B ===== +This project contains a translator from B to TLA+ with the purpose of applying the +TLC model checker on B models within the ProB validation tool. + +TLC is an efficient model checker for TLA+ specifications, which can check LTL properties with fairness. It is particularly good for lower level specifications, where it can be substantially faster than ProB's own model checker + +The following article describes the translation: +Dominik Hansen and Michael Leuschel. +Translating B to TLA+ for validation with TLC. +Sci. Comput. Program. 131, pages 109-125. 2016. +[Link](https://doi.org/10.1016/j.scico.2016.04.014) + +More details about using TLC4B can be found on the [ProB web pages](https://prob.hhu.de/w/index.php?title=TLC). + [](https://gitlab.cs.uni-duesseldorf.de/general/stups/tlc4b/pipelines) diff --git a/build.gradle b/build.gradle index 88e3609a56ebe14eb76303c31379521e641d7c24..28e56efbcb2d751e386f7cd634ab6203db1fd295 100644 --- a/build.gradle +++ b/build.gradle @@ -4,11 +4,11 @@ plugins { id 'jacoco' id "maven-publish" id "signing" - id "de.undercouch.download" version "5.4.0" + id "de.undercouch.download" version "5.6.0" } -project.version = '1.1.0' project.group = 'de.hhu.stups' +project.version = "1.2.0" final isSnapshot = project.version.endsWith("-SNAPSHOT") @@ -26,31 +26,30 @@ configurations.all { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } -def parser_version = '2.12.4' +def parser_version = '2.13.5' dependencies { //implementation(group: 'com.microsoft', name: 'tla2tools', version: '1.4.6') - implementation(group: 'commons-cli', name: 'commons-cli', version: '1.5.0') - implementation(group: 'de.hhu.stups', name: 'tlatools', version: '1.0.2') + implementation(group: 'commons-cli', name: 'commons-cli', version: '1.8.0') + implementation(group: 'de.hhu.stups', name: 'tlatools', version: '1.1.0') implementation(group: 'de.hhu.stups', name: 'bparser', version: parser_version) implementation(group: 'de.hhu.stups', name: 'ltlparser', version: parser_version) testImplementation(group: 'junit', name: 'junit', version: '4.13.2') - testImplementation(group: 'de.hhu.stups', name: 'tla2bAST', version: '1.1.5') + testImplementation(group: 'de.hhu.stups', name: 'tla2bAST', version: '1.4.0') } java { - project.sourceCompatibility = JavaVersion.VERSION_1_8 - project.targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 withSourcesJar() withJavadocJar() } jacoco { - toolVersion = "0.8.7" - reportsDirectory = file("$buildDir/JacocoReports") + toolVersion = "0.8.12" } @@ -58,7 +57,7 @@ jacocoTestReport { reports { xml.required = false csv.required = false - html.destination file("${buildDir}/jacocoHtml") + html.outputLocation = layout.buildDirectory.dir('jacocoHtml') } } @@ -93,6 +92,9 @@ clean { } task regressionTests(dependsOn: extractPublicExamples, type: Test) { + testClassesDirs = testing.suites.test.sources.output.classesDirs + classpath = testing.suites.test.sources.runtimeClasspath + include('de/tlc4b/tlc/integration/probprivate/**') } check.dependsOn(regressionTests) diff --git a/gradle.properties.enc b/gradle.properties.enc index 83e084509404a88a304c64f23a26e07bf592c44d..c1867a27ac7d323a86ce3c5a2d8257a97a0a5b10 100644 --- a/gradle.properties.enc +++ b/gradle.properties.enc @@ -1,5 +1,4 @@ -U2FsdGVkX18nOHLNyyzYk3lwSF0IGgXp8ubFJuMWOPaMbTBmgRPWS/jQT4LO17HP -W5yqIb+NzcYqzLBohg9s9r4XFyoS5ic3TIyPp87IXzgWNh3gKV+F+DfbggwMjiyJ -0gZI+90cmkWXBDW7c3JijLOX2f0NATwuiwHFPau3FCKC0cp7uOArtqkbfZau2how -oP8hzzAue50fahPuBfg8h3OtofJW9x9UCUxxD/NXzD8VZFQabICUjI8mcjEcvaea -MqQn9JuoekIRPDUsUwZ9Er07OkzKXHB5c968S3DUP3w= +U2FsdGVkX1+BEAbjRIB+mXtm8SXf7JkI+WHnEimPW4vLHWrbGs8PY7u+B9BCqO+3 +vmUhdJFfnwJglivtRmt3ecLUpSSG3pZFXrdtnR/eHdLIkbGIIjZRcRTokF66Z2CQ +sWdDhhu2gsRxXOiKSQ/d5MknWHd+zlLoMiWJv3u+EQ3desH/cadBC1RAod7L6Kul +UtSAw5pmAJFaBrRFoOJVvw7hi5ZkpcMB3JTZL2+1Tsxs50m7XAqc5PVdCHpMqVMb diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c1962a79e29d3e0ab67b14947c167a862655af9b..a4b76b9530d66f5e68d973ea569d8e19de379189 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37aef8d3f0c9fffa920a8290320a6c78095e1591..df97d72b8b91fa0e088ae27b1c84a6063481fe22 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index aeb74cbb43e3931a2455a838345c3f6b8131aaa2..f5feea6d6b116baaca5a2642d4d9fa1f47d574a7 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -83,7 +85,9 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -130,10 +134,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -141,7 +148,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -149,7 +156,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -198,11 +205,11 @@ fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 6689b85beecde676054c39c2408085f41e6be6dc..9b42019c7915b971238526075306ffba3b666dd5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/pubring.gpg.enc b/pubring.gpg.enc index fb1dfb132bd34d077723753821aefdc42be64bc2..8ad11824421415e5455b09b4fc68af040a6c190f 100644 --- a/pubring.gpg.enc +++ b/pubring.gpg.enc @@ -1,26 +1,26 @@ -U2FsdGVkX1/MdPD8TmHygEYUS49v1M2eqrSgZK0x8pZ/mIO51EnU4UUelrxxyGN5 -NvnLUPVhm63e2EtzQ3Yhq8f5rb7+2rZ/vwlL6SteBhxH5G0bwb0gCdA2rUiyWKJw -tKwAjizS1TYs1AgU4LpUIQ1iGmvg1WDmuyWpZvJ/2vR/v6rT/5OxHAKzk5MclbDq -a7HfR3XiRmH0zZKMk38zD7id04pDstDO6jfLE1OOay9Rg8qIfUbenHzBlQLiqqz+ -lDsJtzT9UZmtKK0X89TQ7dfS7cmbgpJB11ibLAi+EEJqqkEP2U5BT5qRFsehTp/X -Xh07xOnyMbQXo67cAZ6GkGhw3Wy/71JRRK2ynLg8NmxgTsTqxhcJX4bZ0gCKLome -1QR5B1fhmo2IMpWE8shgk8gm3AKtlo7v8eGzVFmpchrog5HBFclupLUVD5rLj6ei -dncq8jsJ0AlcjFsW+Cyg8/2Tncdi/uwiwsKJdligvXKECAcvuNhFBFPrlPB4Z1KY -f6SQG2LAu5746zCQ29Hpkj5UKiCqCXqdYnG6PCx2ZNkbDSR31GeqK+GbYoahKGxb -VDuBw033g5bvAIeRUuGYC5ua3LhW7Fs5ElUx3feAVjJALtA1FB9mtK2vVwVU/bmS -2f02VBKvYVfZ2asILQJ2HuC157TBbAPEJAu4M+0YR5T9fUiDGLbhDHq4E4vZp+LJ -7WKMecy+zXkvuF13TkxbzmAdh/pQvq8uhLvu24fPbHvzudasZA0n+VwRqg8whzxX -2rodf86Zk3aVPwYPq/o/j1aXRE1zPZHIeZv7mmp+dNvhqS0sjr8fPziUS/MnwzJz -J/K9Z7cXGE1wQIIHnTZGbAa6LI0keV/Ba5IgKLR0CifugjwU4vxHdHEzvo2YZIJI -AVR9oVQMcAx73GWEYlO3SG9IktHamfo76U3FAUtthRZ2D46Us0+LuNsPL92OC7o8 -2+rdgtzulCuYbcVaAFJTrpg4NTHU5uJf8CsDrQKt+1frmV/+lFye7P1OJcREPuQ4 -RA7+1V3A2x8hOiDBo1BBr0MskLu+01l+Lh4YzPd8jTcngn6T7WO5P6689O6Nk4QS -Dg9ubHo3BWdGdJ4nK44qGMa/GfZKG9pShn3Zoq2+1Y5jYCmyjs5/jtV0Zw7NDCTz -5ZBqBU7lxrc0gAUy3dH5IYTmOBNUieZKDYG/sILtBs363am7tQ3sfqgIJEA2nRxI -PnlYAy+JEYKz80zY1c4CFC2gfZzed8499pPMsSjRc8TX8wpe+iE/fL7rjpBdSRi1 -xBSK4BiSOQOLp5Rw5SHDzBpdK9aobNQECCUhkejYEfTi0Xw6v1QZ8U6tNjZQ9+M2 -56VH4wuvYXE++L3SUVEYTJPi3yYC8v+fo80hkm3KF/wIWmeZqmjsRVDHatHxEfld -vzRhO0Lb1CsJo9aq+FAd5E/Ek9skQE1dXoQLRXgFkEJGbmo9hysxz2CB89CaaREW -l/hRW/v3Zqw6giQfe8hOEpyg7yj6xGgEuCuv5Uiz3gLg4NAg8Wvbq0K40ne7ukIO -DrbAkG2+0+TyIBv/ocZJykQ974SD+w0t3qIBeW0q9cxqTtKAX8OAaJhdXx5IiCcW -KpRBcAzZBCC0hKdBTVp/50+ySfcBzHJDnxVzGaWx/DA= +U2FsdGVkX1/ecmzt62K2yKsVlvmQKkfzExhaIo9Zm8/ZobX4Q9asbrssdDbfAdpX +lyIp3wY65EPLcROlrNZqLTjAbcZrPnQyKgCYRr0+s5/0iy6noTWa52EZyPvmP3fw +vsIM/MqFjZCBUhFfvvIb2qNz5+d84lvsOojzeYm+9xSKCx8k24XupcsWuMgfiNla +vmpeUUCPHAYB1clTNn66YdChrQJCcrbnHUmBWms3lSU5waZ5i1dnteaLCLo6M58O +H/7YKOb5cg/0WFE6/l28xFk49ACcAH6i3q3pf99XyPGk+/kvG/Zx+8HvaoG26MkM +HrV60kJgh1t4LBtvadvHk0UyODZJzrH/4ka1XVJv18ZQ5pcLTI6sNEwkM9XjxaU0 +Ik7DIxf6onEaBlk1nRnhXi97gKa7+XjVR82pLXgPEn5HrAe+ObX1UL0VqfJw7EXs +Nb2ZVciC/ugfi3UiHuOtFmImo+MRLXvvqkpW49VfO5GwBBpmjM9PcXdRzdtU8USp +Z+KXXBoUPfZupCpty+ZCq8uBEMW93ifeqOLOqcr8B496LrPOC+T4D/MOh+1Pdpy+ +3YmzdfwttqKXNULhiW/loljKoKOBOjO6DDWwyEH+4LEuZYgXdC6nfedchU+F5ZQw +ORtyrkznV7baoNR/UDT33qz0c3fEtoWmPtiuiClHN12CoXWamK7dwBKP64aPL5Xy +UaYsrbjhMhW3/miVx6NgIv0iq8B/aUrJIXVdGWycVJVciRbgk1Px6z1lo3GOaZad +APqExffMHUOQZCjv8AC9tKsy2heog97Q4jUwOCHdghfmKK16ksy4plDaVN322uOG +S3mkfJLxw/2oUeAA8IFARCZ1FoCINPKxiRevPXhoizRNa7WzmQ4jT9C+BWDJeitn +LrA7fMmTpW0z7oaQez2VTSFg5liDtozp7Dp+d5MBA9Rg4B69F121FIt3MXWACHFl +5YW2+Sa6czh8P7eZQ4lRGOl8Y56NAE72n5l15HUdxrnEowwREuHAmWVdWCi16oTJ +JUqcSv3vu4WZQo3XhoB36ll0gvYZezlzoxpSqekBwlDkKCqevhncyu0UefG9fApu +g/2gDmQIVeAMfKytEyAomXCNiFriesqPBAyt3ZRivbWCMeBGT3KuMO2BIigfW7na ++BdpdeCF8KIEiOq69Ulaw6wo2lTOlP+utuD6D3iB0ATsvr18Bj9CXN7lloQD4tmw +DTUxrYBFjjtK6/SINHq0CwCgY968QdL+muk1A1xIiOK4ELNSLK16qIHUKYN5G7pr +eGNRD0KGeg64u42o+R1bZaYOWEqDHw9gWP9uuDp+M31T2uz3+NZS7JOmqpwh1VRy +4hW7BEhLO+C/A+feWeuXq5PXlMaeEE0+L8QE0nvto3N3HqsiwXIgg54AsQEkRCxp +uybDyfvAc4ni+GTd+8g0oUilzxa/oHGGzD386/aZDVWXhNiFZNXfr2LJljMW+lRT +7A5z/IIegoN5lSNy4IwbJY4WSRMaZ3jX7zM/t5IAyeB2/BXuiKspJ+XKhNwib5Mo +NKuwogypLpPux7968PkRHiOk3ndizKTUQj4RF52dWqW7ekbYelK1fcJXxILXDYi7 +8i/H7c7cUzvYvmnHe+2PArs2yVUL+fBrrsdXSaaswMs= diff --git a/secring.gpg.enc b/secring.gpg.enc index 048652a825198ed70f778f2b82600b83be9d5d3e..087d41d8e55ca33bbdbacc52334567604dfe3398 100644 --- a/secring.gpg.enc +++ b/secring.gpg.enc @@ -1,55 +1,55 @@ -U2FsdGVkX1+qD9zNt5PsTWUNPv0+h3MZr3LMQniTSXNJ70iaxTv8TOQ2EFQM42X0 -IKPutnofk+e17tRWJch3XTzTI95sU7s8NgtrorS9cNJQMMpZrMSNGt6jHbLGC6jL -F4AWjk3fNg4s0OVPvVD4ZXbdLm1BJaNuz094kRGNNTYPrFapxkPr6WVDjnZsh3bh -S5xhQ84hSAyfXKShs8HidN6Mf6XZvRgVsXg87SeCNQlTtyU+k8o5/COXZ35XhNjY -NUEOSaSaBbhC16fNC8rWYTqcOsrypiikuZAT+qo2ZfMw3/SYUyc9q9qPfQvITJqb -YtfQsdfQEarI0skRBZLuNs8OOWMh473YaMqicaNfOUTtPm3NPElZNAIVyM6wp3lh -36Ovib377R0IAvsSg5ktSHWbkPOY1MqDusHRHW5s5jjrjAtKyi3iWjQ4L4Mf67lj -ZJ9b2YQpdqQQOpZg8nRghk/Dqw2XGWc/84LgnaTCdSTsYSyZbDkYvLbyNzoNbcx1 -i2BOUqDaA9N3lGdgSqrHLjVdH3LegpCaEBsi3I8ZdDVfZMHckujYI7+/rDqzDxQ2 -btbHt9LKcciOpWZvrD83R5Uq4WewWrkx6vKUYwQAklKu4SkKUz/Q+P4esWWfgMcy -XXhhzMhvhx9Hsham5AznWU5oXDhCxdrdpXtI56Jepa444M9e7JaoszaQ5V0rHFhA -F2Ko7vDlk1LRjJ1f27T3Uaj26jspyCiaAi7kVBTriCVGp7yEoAJ5EBeOOPKSzzOa -pxyzYuKQlf+nQoo5t8TPpgLIPJbip70n0HNkKDc2cj8102ZeKgGWkpnNawrtgkjs -b5DK3f+SjuZCWGnXZ2pcM01NIAXOCnw7hCH06z5hXmzK/jDDbckWL/F7sVtO4n7Z -yICynW0m2EkzMpU4yPC5f5h9iNpNgV1xirjZ5F2QbiguvtAZOo0YSGtE6lO/22uI -jgXW5uMzkh3doBatbEsJYh8dGzrCqq1leC8b+MBOM8Xby4wkCgSSCOzclF9AIRe6 -axHGfFtO/wOv0Z/6CeuREvw38MIjozVIZomjddEj9KLW1/30ljksvhDnv2pS0vVm -nAvYiXvtuvMwDzmFEpsAqinyFbzS3lCMzlqRoATFbjUGAh29Xz9PHsLHb0B9KjRD -1/rz3BVhzNaYEvCMX8J0M5mzjAzTaB8eWkQnZ+wLfmUJlvt6XFxDuLbcNGmCZ2th -8NNfvly6Awbkln2R3wism0oIDUnO8KrUJmVtCcbOIiEkrsOEq62oF3Ndof5jKHUx -2KcjuzSrKiXoYoVH4uTh2HiKHVB71yZ8Fpwrbda16AMrmpA35urKeEmAjTsmT0iT -Plxnd4cPfqSxAesGOpz5jhRjPc/3FqIYvewf1eINUHteduDwLqeA0SqBcDgW6YIO -LRPQhJdsDnpmV5NKXbSHChRAsk+4CrCS68WNJ/RrY1NhuFktjHQ+mHyg886YMnmg -bYRd9CKmlYDBVsgpFJFT7wDMoCWZ132flqegu8ojsdjXD/2i18kcyZgFx/YFimz9 -u2NRVOJnU0ec5tTk0HNi3q5wG/pgIWj8et2HDSDBr2dhBc5s+s9EhL3JXDr3SoEp -bW41GA+G7l+FPKakOgDgiw2VBi5MmIPMwDRzhi/VD3mrI8SfKFDQxq1Ro91dy0sO -cQ4Ku1esMojqNJO+sPUOm0LYj3BgL+bUQdc4Vj4gvo/uDEk7SrPloDaMPjzbQsQ4 -wJ+NRuF82NvagdA25vEMxLD3O3aD7wsQA/Fsbh04GLwbGkH+Kl9QGmMVMHJU2Dn/ -1owCuIvNRYZU587HQXDitM5Be7+EixE/90PLuAioe8iNDiCHUPwiYMHge5ZNZlbk -agN4KjmkEpCh0XwOLvD9F5PDji8dAp6AOmZhQK+y0XTGGQCWD2k6tBFD94Ux4wOi -J18zIEDeRJWZA/WiyqEihVIRNcq7NZQRfv3PsSbU8wFbVg379yJftfIdXj8fJFcI -7gKK7gYv2A6K9kS6pNSN8kSWBsukiz0/njiPZH1wjyeSrONueacJ9guk9hzTeN68 -iD00zcdtukC6ZtxXRB9XOAbXTGhbyWrdb5ATCmJLFG8riUTJVo5DIyHzCg4rCRef -2yq5Pe1MVsV8960AnkE1iyin2lMebzJJL8ridlHmzhaNIRSSGxstv1tnaZL1xVWV -c2pLWkch6uEzdyC5Zyd5Xi56zyxUxxCYPEPA9lortKgW7KdYULUvTBHfRoGAUqjZ -6yHl37DF1MWFHmV4Dk1yHNP7uVazF+7c1hJTvqop/ytFkgIEhLq8SHWBEHG/sGVi -R11UfpoVHdkT3KJm6Y/tml9SLxES65ENzLGPTKVUAaHKImADXrMI9slU+lUMHDr8 -MwKx3+4xSgUUYWL2+YfayURNK6LIUskmsOlGy212z1B/pJc8DvrH9rqj6NtBaQlZ -lR6A9eiG3i88N2PvibxMuHW+ye0zlbiktqArWQAhNgt9mM05BQSb2Ce55cl8yLCD -+3eSAIFUKQhn4aHNaEutGD7q02bjX1pcUymM9NV2WxHtG5dQPa8eWRXKwJca3V6w -WKC/ve1HXsCunjW5mc2FvtsqqKUANzRjTV2fkbQlMdVfdThy+MIxJs0P8XMbyxT7 -tjwt4tuq42ZAQkj8dLL2j1z+/otzH3LtfYjl3CjDjWPlfVFJn+1lISQDBdzWPYe/ -xnhNn2Gsx0jWv1vX0dbxD8gyXP68yS3KLPTBb6DoTbjW+0LraTLlHSw2rNJ/zTsM -5hcf7PnuEr3c34bVjP2XLjrZ6qT0+TEXJ8vR6ptuUL/GFREG8ByfBG4SFphR1Nkr -iuySq+4awgKwmXrfiVdBQPrn+UWfH/UQh6Jt2J0xvRwcs7/COO5LcWqjD4bSCw9a -CfSkivrrEDmeE4aruA1eOeauVbRcqwtMuzCV7Gq282LKambmnKiWvrk9wJnF2IaQ -wV8rjmBM08sf+93/P+TbYhY4e/z27+ml844HwoNsivuvmo70z8nYNnFXKKOewZby -Vw0I3JX/2vkHllMFtLcJqnQLD8zJR2SclkUnWv4S519qR0sg9kzFvggTvB740KDu -Ohu1wIeHkTv9ZnCfu/7gK3lxNobyV2+2UhgBB4/njI/9mb4BnOJkaTG7HvJA+Pks -BpSL7jOrmTixSLzt6rsLeYpp8J+A2+uKL5Q1t97My/yhIKjC67LuWVfKovB+5/Bk -/C/FuDqeKDeLOl/lBs1ntQM4TDtb8uVNSmKKdlj4h+dp7J5ZIzHuKDRRw7HcWIPw -3ThPVLFQUoDUsnRxTkenqWA4yUov0UPwpwOBswZQFqFwoX9BQ8hqk13c9P2AhVMZ -2wR5J5cbH3sum2Np/cZUOXuqvcoQGQNyKb1t8PXsvGc3LaMraxRNUcIVJJzUr/eC -oja8ldCr68ZwD/M+CZgQNGr1/5+78tzKdD5432/pZ6W5ZOM36xzyI71b/tZkB4S6 -ATF+WE2brPM5g2Wr4T+xKA== +U2FsdGVkX1/uZ2q881m1pVQtzJ0DILJqtO2ZEJOotiBebJg4SmSM4TkLeSgTDFoD +m3fsZdrdbTrOqpNjdCySadS2IwibzJjG8cRFxnetJNUdfpWGFb67kKx/Han4QaIY +d9bvEAkg02nL3suJTa4WKVl70gjiXSheOXgWHi+L3mEGzJewORIIYBv1BE60zxjB +72SvpfrboYxFBCahZJ/GAiNvw4aqD0Wj9G5CJlM6xY0gGTn3dXuWkUC+sciQp9UI +rRSF+r/RMRvbUAPZY3F2S07wMSzIBct9INyhc9kQptRwhuy9BAAdfxVaMxEK3a2P +cM7mHacEmE242/4a28unvcDnsuyV3NW74pt7f2v+LFlPvM8Cw9tpeKtFCRXfREJR +g32dDJBo+4zSa3qLx7n4gsUFaKTDJWPtAPe0pkMLa7GrdoEVIkaIl4m1ET8+M6t4 +sKrBKP7neVnjjkSPRroxpiSQ7MLECeyj3MNUB/r/hsLg1ZLc8n90b1vPKqd4DIpJ +PtiIcamt6K8gvAIOwUZQqdpJNNTqCLV9DnKyj5I/U8RpHAXsBe5eawX2WDxA/Ywf +INzBibO9yUpg25OtlsHRqdcyHNmDRMAVUOWtzqa+5lGWIF3h0qWOY8BEqHf7TkjO +O/2qPBqLSmpRcOdgUg9G/5Snpb1xo4NXEZ2kj8GC+Rf61stI38QVScLTsPSR+QKK +9VgCSg1cQTmhQnwZLQw5pB7SdsFPtwwq62YM5E2xzZwr9f9eJVXTfIQlwjM+t7cH +nFbyC+3ywLnvlec/NEeA4DOH5QfJ2vRUQmcXuzmuBi0vGSriVd3U4CKiRKsq7umo +nFpo6y8i7qr4Vj3oIgRIj3yyzYEnaSyJXRJ2mhp3e4fqrMMD7MFrAZ4syKgAJ1Xh +qFbfovebhPbA4NtLrehmZ0r9F1ovowo1X8fwqpoqaKO1LVYQkWC1N/Tkg0ASUlTh +pF0O94r7sMv6pD7vvBvwsfZWxt6qWHVD4H6JU4ySwWHOFiFs7YWPbQIcqaw1Y9R+ +sZncQ7Aul/8HGhYhQvklsrK2Yt5nKAQCibST8UinICyAbEWnHnRLaLleB45BiAUy +injdzUjwy2PO7sOnUa7Nf37QuxZGMIMqETapc5ONIz+CAqGjfOC1BGSB6vZmUCNn +W3kpFHbznGTe0zAoPYFhsfnwOWc/m2xUJRRwovVYGQc+PLGEUsMa9JhxwEyb6EUg +bXMsyfk2RBZYEV7bWqML2Nyv71nBuMDjCkAju3gUCaWeG4OVjLTjvvTTNsKWqzKt +vevEgTteynQrUi+CvsqY1fcwyZcmqTBIen+pUYz8mK+JXfL5ppafvuRGZBWMtJW0 +Q+3x7HLGtbNO6MNoaK+dPfp5ekQ7eztRFEwTPRTuvqnVBGmgot4HkkxB3noASlCb +xEXEjSYmQJA8Y+B0OGG8CNyKnS/ZeHgqA0K9+xPLuWmJBSEGAgpe6knBdE2+5Qqp +/OgfTKnrCjaVZPeWUG+EwbnUriUKJfTM0SIixJwla9ml+8pzTU1qkRLgD1aychM7 +91mxducI9ZsbGAa9aH4SZWU8PC3EPoMOxqN88kZNcfb7AjWMLOdCcgHUm+zRZ/46 +zJaS3MAXDdxLmTweT/seL/7VhKvfMSo+qKX1ALSneXpYtAT/XjrIOidhCr9et9eu +SzPdQt24lwcyuGQPIBDYt9NuMBqjFmOE6X3O3CMr4G5d0YmDJuWDZvvCEtGrQjc1 +2fREnWTzgkIvOxlYlrR0cczUpzRiAgCfU3ujHRXV+Fqch3RpxmwWz4FGsoJfJ9+a +LNRGtMn+X9Tt/Vx9J1RlPwHJ6U3gS853MXGLXzXFKobqZL3XrMhT00kN0sONCxvc +L17s62zThzeENKZPQxSuA2GVeR3ucip4AhPgFsCCB3m/aIPNZ45/PpRMIFVbijIz +u3XTxv6DN2tp7rDyerRvhfNkVxdu0G8AZ18immyT2wkxnuM4SZODBFK32C6iY2Sx +LU5GgTCSvy/ze5/DRXFhG6mcC9iUWALpfYvCGGwpwdK0MM/Xqd4t7X/kVhcEGljF +UPN09Ja6OqYO47yZUdTUp4L+0FkHnl3wqQaL23e92mb+LpqBYUsdH9PBMAHZ6YA6 +OlDNP9n0xwoPHSz4od/6lNA93AmpVOfcrJ2N9J4GMPX44AATDLbr3Hwd8lSxvVD8 +oITXp1lZcLzpDo8AHEF/t/MkahaIxTeyjX6jAy2HB5IIXFn5IopAO5gNLS1jmT0I +4d+9u1JxArjQRCjV0c5103SLzVFrYbTVMT7iegCAXjQ0CR3RjGQNna0KMA7Yteoy +gTb7lNDrBjfVk3LkqsBH7bpCQik9lqmcWhYP+ry7wbAK99v/FtzhHqBjyQYHmEBC +Zepft6grJ1JiNOwhTs0/uLQNamuMD1qNGZfta/7CQYzLARvy78DXXyfiM0vc9HeI +cdBwm0nmn2mL3xpKZbQFUNJtzTZTUM4K+H+4Ua166Plil4Gmb2p8BM/Ulby27xDM +OvKgofUrWorPny3kPgjlNXpWAaxGPgcrC6/Zx2mwdUBSmsGAe9aGVMk1wIN/KKdz +uvpAYnlQu26JK39BVVO3OR9v7S3kALxGlN9TCxszWfHiq9wR/BHrZzud1XoCuzZA ++YNDLIWIkie5B7WkF6o+7HnO6/G7arl2gmTBK/i5f/vfZsnj077kQz6TPxt+/k6I +RLWVzUvUDtqSlAO9Wnbi0gajRcsjREVrGiS0kh120x4JRJfEdVmDs/MDPK+iM7ov +mEOgGTIa73SxZZnwqG9j6uggY6M9m/ZO0uPNTEt+jsbQ0NZ9prpI+2/6A8QAX6RE +ug7x+98jjXf7vboTEJLTHJxbuBxJLhJjOqY1Nq0I7GahpPGZMo9yo4Ty78bF4E57 +OpT/Q0/wTVSyK9fHPQrRr5zFjvwHmCCs2wWpc76Mv2OThmzVudgyJAoUPENxLSrA +RylkDiihi4PacfjaClbKJJ7K7cgU7KqJQgwS9AM4H8sRqQsZZX/f5UMAVXPRj6u0 +qnoH9gxIYAzvm6ceVklagTk09IWCiWqY0NGELL6+plxzjkJuXX2LstfXiHY7g29P +FLnneZ0kNWog2ynKUVBFkdEVdS6K0aQ0xqUFXAwbNvrcpiJeY9RufQcBUlZm/fPb +m26i9V+sL3CcHRbX4qa/QRsQ7DdjdSpOJAt0GQUco3AGfW6Z1koIjSswr0IA41no +1A35JdElJm+lt0pHA9QWBTewNfJkXPR/GHvqUdc1sTDDXa2binNHFWhb+ydX2aQ6 +z8ceydjxEt6I3mdK89GZsc/839ctCkeevrjLIC+wAxOviGNJanfyt25BirCgntpi +sLyqYz1nesHZeheyKQBw6y5oYI0EAtVX1ifwSvYgAjbFb1rUmeZl+NWgU14eskyT ++0SdoUgo7WNuJelmyRRoIwTgaV5p3boreRWmdA0oiIKowo6dFE+PzU/cy0dBZtL+ +xkXQZ8J6POdTEt4A9Vw6BQ== diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..b7adac996996acbb28959b542bb569f56823db47 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "tlc4b" diff --git a/src/main/java/de/tlc4b/Log.java b/src/main/java/de/tlc4b/Log.java deleted file mode 100644 index 452fd6016236a52f75ed857966725f9436f14c95..0000000000000000000000000000000000000000 --- a/src/main/java/de/tlc4b/Log.java +++ /dev/null @@ -1,63 +0,0 @@ -package de.tlc4b; - -import static de.tlc4b.util.StopWatch.Watches.PARSING_TIME; - -import java.util.ArrayList; - -import de.tlc4b.tlc.TLCResults; -import de.tlc4b.util.StopWatch; -import de.tlc4b.util.StopWatch.Watches; - -public class Log { - - private ArrayList<String> fieldNames = new ArrayList<>(); - private ArrayList<String> fieldValues = new ArrayList<>(); - - public Log(TLC4B tlc4b, TLCResults tlcResults) { - - fieldNames.add("Machine File"); - String machineFile = tlc4b.getMainFile().getAbsolutePath(); - fieldValues.add(machineFile); - - fieldNames.add("TLC Model Checking Time (s)"); - int tlcModelCheckingTime = tlcResults.getModelCheckingTime(); - fieldValues.add(String.valueOf(tlcModelCheckingTime)); - - fieldNames.add("Parsing Time Of B machine (ms)"); - long parseTime = StopWatch.getRunTime(PARSING_TIME); - fieldValues.add(String.valueOf(parseTime)); - - fieldNames.add("Translation Time (ms)"); - long translationTime = StopWatch.getRunTime(Watches.TRANSLATION_TIME); - fieldValues.add(String.valueOf(translationTime)); - - fieldNames.add("Model Checking Time (ms)"); - long modelCheckingTime = StopWatch - .getRunTime(Watches.MODEL_CHECKING_TIME); - fieldValues.add(String.valueOf(modelCheckingTime)); - - fieldNames.add("TLC Result"); - fieldValues.add(tlcResults.getResultString()); - } - - public String getCSVValueLine() { - return getCSVLine(fieldValues); - } - - public String getCSVFieldNamesLine() { - return getCSVLine(fieldNames); - } - - private String getCSVLine(ArrayList<String> list) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i)); - if (i < list.size() - 1) { - sb.append(";"); - } - } - sb.append("\n"); - return sb.toString(); - } - -} diff --git a/src/main/java/de/tlc4b/MP.java b/src/main/java/de/tlc4b/MP.java index e2088d513273f929bb7444baeec14b95bc4ffae9..609c78a1aa5989944559ea0c1a2bb0ebd13a753d 100644 --- a/src/main/java/de/tlc4b/MP.java +++ b/src/main/java/de/tlc4b/MP.java @@ -4,8 +4,8 @@ import java.io.OutputStream; import java.io.PrintStream; public class MP { - private static PrintStream out = System.out; - private static PrintStream err = System.err; + private static final PrintStream out = System.out; + private static final PrintStream err = System.err; private MP() { } @@ -15,6 +15,26 @@ public class MP { err.println(errorMessage); } + public static void printlnSilent(String message) { + if (!TLC4BGlobals.isSilent() || TLC4BGlobals.isVerbose()) + out.println(message); + } + + public static void printSilent(String message) { + if (!TLC4BGlobals.isSilent() || TLC4BGlobals.isVerbose()) + out.print(message); + } + + public static void printlnVerbose(String message) { + if (TLC4BGlobals.isVerbose()) + out.println(message); + } + + public static void printVerbose(String message) { + if (TLC4BGlobals.isVerbose()) + out.print(message); + } + public static void println(String message) { out.println(message); } @@ -27,8 +47,17 @@ public class MP { static final PrintStream origOut = System.out; public static void changeOutputStream() { - MP.TLCOutputStream tlcOutputStream = new TLCOutputStream(origOut); - System.setOut(tlcOutputStream); + if (TLC4BGlobals.isSilent()) { + origOut.println("Run TLC..."); + System.setOut(new PrintStream(new OutputStream() { + @Override + public void write(int b) { + // ignore + } + })); + return; + } + System.setOut(new TLCOutputStream(origOut)); } public static void resetOutputStream() { diff --git a/src/main/java/de/tlc4b/TLC4B.java b/src/main/java/de/tlc4b/TLC4B.java index 4efe0950a58f11c2258fa6e9eb2d28223117bc55..45d56b841f849b552bf35f54859546760d1851a6 100644 --- a/src/main/java/de/tlc4b/TLC4B.java +++ b/src/main/java/de/tlc4b/TLC4B.java @@ -2,36 +2,45 @@ package de.tlc4b; import java.io.BufferedWriter; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.util.LinkedHashMap; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; import de.be4.classicalb.core.parser.exceptions.BCompoundException; -import de.tlc4b.TLC4BGlobals; -import de.tlc4b.analysis.UsedStandardModules.STANDARD_MODULES; -import de.tlc4b.exceptions.TLC4BIOException; import de.tlc4b.exceptions.TLC4BException; +import de.tlc4b.exceptions.TLC4BIOException; import de.tlc4b.exceptions.TranslationException; import de.tlc4b.tlc.TLCOutputInfo; import de.tlc4b.tlc.TLCResults; import de.tlc4b.util.StopWatch; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +import static de.tlc4b.TLC4BOption.*; import static de.tlc4b.util.StopWatch.Watches.*; import static de.tlc4b.MP.*; public class TLC4B { + private static final String CSV_DELIMITER = ";"; - private String filename; - private File mainfile; + private File mainfile, traceFile; private String machineFileNameWithoutFileExtension; // e.g. Test of file foo/bar/Test.mch - private String logFileString; + private File logFile; private File buildDir; @@ -43,126 +52,132 @@ public class TLC4B { private String constantsSetup; public static void main(String[] args) { - System.setProperty("apple.awt.UIElement", "true"); - // avoiding pop up window - - TLC4B tlc4b = new TLC4B(); try { - tlc4b.process(args); + run(args); } catch (BCompoundException e) { printlnErr("***** Parsing Error *****"); printlnErr(e.getMessage()); - return; + System.exit(-1); } catch (TLC4BException e) { printlnErr(e.getMessage()); - println("Model checking time: 0 sec"); println("Result: " + e.getError()); - return; + System.exit(-1); } catch (IOException e) { printlnErr(e.getMessage()); - println("Model checking time: 0 sec"); println("Result: " + "I/O Error"); + System.exit(-1); } + System.exit(0); + } + + /** + * API method to call TLC4B directly in Java + * @param args same arguments as for the CLI version + * @return results of TLC model check + */ + public static TLCResults run(String[] args) throws TLC4BException, IOException, BCompoundException { + System.setProperty("apple.awt.UIElement", "true"); // avoiding pop up window + + TLC4B tlc4b = new TLC4B(); + tlc4b.process(args); + TLCResults results = null; if (TLC4BGlobals.isRunTLC()) { try { - - TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, - tlc4b.buildDir); - TLCResults results = new TLCResults(tlc4b.tlcOutputInfo); + TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, tlc4b.buildDir); + results = new TLCResults(tlc4b.tlcOutputInfo); results.evalResults(); - tlc4b.printResults(results, TLC4BGlobals.isCreateTraceFile()); - Log log = new Log(tlc4b, results); - tlc4b.createLogFile(log); - System.exit(0); - + tlc4b.printResults(results); + tlc4b.createLogFile(results); } catch (NoClassDefFoundError e) { printlnErr("Can not find TLC. The tlatools.jar must be included in the classpath."); } - } + return results; + } + /** + * Check whether TLC4B is applicable to the provided machine. + * This method has no return value - if it returns without throwing an exception, then TLC4B is applicable. + * Be aware that this method may take a long time to run for large/complex machines. + * + * @param path path to B machine file + * @throws BCompoundException if the machine file could not be parsed + * @throws TLC4BException if translation fails for any other reason + */ + public static void checkTLC4BIsApplicable(String path) throws BCompoundException { + TLC4B tlc4B = new TLC4B(); + tlc4B.processArgs(new String[]{path, SILENT.cliArg()}); + tlc4B.translate(); + // tlc4B.createFiles() is intentionally not called here! } - private void printResults(TLCResults results, boolean createTraceFile) { + private void printResults(TLCResults results) throws IOException { printOperationsCount(results); // options - println("Used Options"); - println("| Number of workers: " + TLC4BGlobals.getWorkers()); - println("| Invariants check: " + TLC4BGlobals.isInvariant()); - println("| Deadlock check: " + TLC4BGlobals.isDeadlockCheck()); - println("| Assertion check: " + TLC4BGlobals.isAssertion()); - println("| Find Goal check: " + TLC4BGlobals.isGOAL()); - println("| LTL formulas check: " + TLC4BGlobals.isCheckLTL()); - println("| Partial invariant evaluation: " - + TLC4BGlobals.isPartialInvariantEvaluation()); - println("| Lazy constants setup: " - + !TLC4BGlobals.isForceTLCToEvalConstants()); - println("| Agressive well-definedness check: " - + TLC4BGlobals.checkWelldefinedness()); - println("| Prob constant setup: " + TLC4BGlobals.isProBconstantsSetup()); - println("| Symmetry reduction: " + TLC4BGlobals.useSymmetry()); - println("| MIN Int: " + TLC4BGlobals.getMIN_INT()); - println("| MAX Int: " + TLC4BGlobals.getMAX_INT()); - println("| Standard deferret set size: " - + TLC4BGlobals.getDEFERRED_SET_SIZE()); - println("--------------------------------"); - println("Parsing time: " + StopWatch.getRunTime(PARSING_TIME) + " ms"); - println("Translation time: " + StopWatch.getRunTime(TRANSLATION_TIME) - + " ms"); - println("Model checking time: " + results.getModelCheckingTime() - + " sec"); - // MP.printMessage("Number of workers: " + - // TLCGlobals.getNumWorkers()); - if (results.getViolatedAssertions().size() > 0) { - println("Violated assertions: " + results.getViolatedAssertions()); - } - println("States analysed: " + results.getNumberOfDistinctStates()); - println("Transitions fired: " + results.getNumberOfTransitions()); - println("Result: " + results.getResultString()); - String violatedDefinition = results.getViolatedDefinition(); - if (violatedDefinition != null) { - println("Violated Definition: " + violatedDefinition); + printlnSilent("Used Options"); + if (TLC4BGlobals.getDfidInitialDepth() > 0) // -1 if disabled + printlnSilent("| Use DFS with initial depth: " + TLC4BGlobals.getDfidInitialDepth()); + printlnSilent("| Number of workers: " + TLC4BGlobals.getWorkers()); + printlnSilent("| Invariants check: " + TLC4BGlobals.isInvariant()); + printlnSilent("| Deadlock check: " + TLC4BGlobals.isDeadlockCheck()); + printlnSilent("| Assertion check: " + TLC4BGlobals.isAssertion()); + printlnSilent("| Find Goal check: " + TLC4BGlobals.isGOAL()); + printlnSilent("| LTL formulas check: " + TLC4BGlobals.isCheckLTL()); + printlnSilent("| Partial invariant evaluation: " + TLC4BGlobals.isPartialInvariantEvaluation()); + printlnSilent("| Lazy constants setup: " + !TLC4BGlobals.isForceTLCToEvalConstants()); + printlnSilent("| Aggressive well-definedness check: " + TLC4BGlobals.checkWelldefinedness()); + printlnSilent("| ProB constant setup: " + TLC4BGlobals.isProBconstantsSetup()); + printlnSilent("| Symmetry reduction: " + TLC4BGlobals.useSymmetry()); + printlnSilent("| MIN Int: " + TLC4BGlobals.getMIN_INT()); + printlnSilent("| MAX Int: " + TLC4BGlobals.getMAX_INT()); + printlnSilent("| Standard deferred set size: " + TLC4BGlobals.getDEFERRED_SET_SIZE()); + printlnSilent("--------------------------------"); + if (TLC4BGlobals.isTranslate()) { + printlnSilent("Parsing time: " + StopWatch.getRunTime(PARSING_TIME) + " ms"); + printlnSilent("Translation time: " + StopWatch.getRunTime(TRANSLATION_TIME) + " ms"); } + if (TLC4BGlobals.isRunTLC()) { + println("Model checking time: " + results.getModelCheckingTime() + " sec"); + // MP.printMessage("Number of workers: " + + // TLCGlobals.getNumWorkers()); + if (!results.getViolatedAssertions().isEmpty()) { + println("Violated assertions: " + results.getViolatedAssertions()); + } + println("States analysed: " + results.getNumberOfDistinctStates()); + println("Transitions fired: " + results.getNumberOfTransitions()); + println("Result: " + results.getResultString()); + String violatedDefinition = results.getViolatedDefinition(); + if (violatedDefinition != null) { + println("Violated Definition: " + violatedDefinition); + } - if (results.hasTrace() && createTraceFile) { - String trace = results.getTrace(); - String tracefileName = machineFileNameWithoutFileExtension - + ".tla.trace"; - File traceFile = createFile(mainfile.getParentFile(), - tracefileName, trace, false); - if (traceFile != null) { - println("Trace file '" + traceFile.getAbsolutePath() - + "' created."); + if (results.hasTrace() && TLC4BGlobals.isCreateTraceFile()) { + String trace = results.getTrace(); + String tracefileName = machineFileNameWithoutFileExtension + ".tla.trace"; + traceFile = createFile(buildDir, tracefileName, trace, TLC4BGlobals.isDeleteOnExit()); + results.addTraceFilePath(traceFile.getAbsolutePath()); + println("Trace file '" + traceFile.getAbsolutePath() + "' created."); } } } private void printOperationsCount(TLCResults results) { - LinkedHashMap<String, Long> operationCount = results - .getOperationCount(); + Map<String, Long> operationCount = results.getOperationCount(); if (TLC4BGlobals.isPrintCoverage() && operationCount != null) { - println("---------- Coverage statistics ----------"); - + printlnSilent("---------- Coverage statistics ----------"); for (Entry<String, Long> entry : operationCount.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue().toString(); - println(key + ": " + value); + printlnSilent(entry.getKey() + ": " + entry.getValue().toString()); } - println("---------- End of coverage statistics ----------"); + printlnSilent("---------- End of coverage statistics ----------"); } } - public static void test(String[] args, boolean deleteFiles) - throws Exception { - System.setProperty("apple.awt.UIElement", "true"); // avoiding pop up - // windows + public static void test(String[] args, boolean deleteFiles) throws Exception { + System.setProperty("apple.awt.UIElement", "true"); // avoiding pop up windows TLC4BGlobals.resetGlobals(); TLC4BGlobals.setDeleteOnExit(deleteFiles); - TLC4BGlobals.setCreateTraceFile(false); - TLC4BGlobals.setTestingMode(true); - // B2TLAGlobals.setCleanup(true); TLC4B tlc4b = new TLC4B(); try { tlc4b.process(args); @@ -173,256 +188,287 @@ public class TLC4B { } if (TLC4BGlobals.isRunTLC()) { MP.TLCOutputStream.changeOutputStream(); - TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, - tlc4b.buildDir); + TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, tlc4b.buildDir); MP.TLCOutputStream.resetOutputStream(); TLCResults results = new TLCResults(tlc4b.tlcOutputInfo); results.evalResults(); - tlc4b.printResults(results, false); + tlc4b.printResults(results); + tlc4b.createLogFile(results); System.exit(0); } } - public static void testString(String machineString, boolean deleteFiles) - throws Exception { - System.setProperty("apple.awt.UIElement", "true"); // avoiding pop up - // windows + public static void testString(String machineString, boolean deleteFiles) throws Exception { + System.setProperty("apple.awt.UIElement", "true"); // avoiding pop up windows TLC4BGlobals.resetGlobals(); TLC4BGlobals.setDeleteOnExit(deleteFiles); - TLC4BGlobals.setCreateTraceFile(false); - TLC4BGlobals.setTestingMode(true); - // B2TLAGlobals.setCleanup(true); TLC4B tlc4b = new TLC4B(); tlc4b.buildDir = new File("temp/"); tlc4b.machineFileNameWithoutFileExtension = "Test"; StopWatch.start(PARSING_TIME); - MP.print("Parsing... "); + printSilent("Parsing... "); tlc4b.translator = new Translator(machineString); StopWatch.stop(PARSING_TIME); - println("(" + StopWatch.getRunTimeAsString(PARSING_TIME) + "ms)"); + printlnSilent("(" + StopWatch.getRunTimeAsString(PARSING_TIME) + "ms)"); StopWatch.start(TRANSLATION_TIME); - MP.print("Translating... "); + printSilent("Translating... "); tlc4b.translator.translate(); tlc4b.tlaModule = tlc4b.translator.getModuleString(); tlc4b.config = tlc4b.translator.getConfigString(); tlc4b.tlcOutputInfo = tlc4b.translator.getTLCOutputInfo(); StopWatch.stop(TRANSLATION_TIME); - println("(" + StopWatch.getRunTimeAsString(TRANSLATION_TIME) + "ms)"); + printlnSilent("(" + StopWatch.getRunTimeAsString(TRANSLATION_TIME) + "ms)"); tlc4b.createFiles(); if (TLC4BGlobals.isRunTLC()) { MP.TLCOutputStream.changeOutputStream(); - TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, - tlc4b.buildDir); + TLCRunner.runTLC(tlc4b.machineFileNameWithoutFileExtension, tlc4b.buildDir); MP.TLCOutputStream.resetOutputStream(); TLCResults results = new TLCResults(tlc4b.tlcOutputInfo); results.evalResults(); - tlc4b.printResults(results, false); + tlc4b.printResults(results); System.exit(0); } } + + private static Options getCommandlineOptions() { + Options options = new Options(); + for (TLC4BOption option : TLC4BOption.values()) { + options.addOption(option.arg(), option.expectsArg() != null, option.desc()); + } + return options; + } private void handleParameter(String[] args) { - int index = 0; - while (index < args.length) { - if (args[index].toLowerCase().equals("-nodead")) { - TLC4BGlobals.setDeadlockCheck(false); - } else if (args[index].toLowerCase().equals("-notlc")) { - TLC4BGlobals.setRunTLC(false); - } else if (args[index].toLowerCase().equals("-notranslation")) { - TLC4BGlobals.setTranslate(false); - } else if (args[index].toLowerCase().equals("-nogoal")) { - TLC4BGlobals.setGOAL(false); - } else if (args[index].toLowerCase().equals("-noinv")) { - TLC4BGlobals.setInvariant(false); - } else if (args[index].toLowerCase().equals("-noass")) { - TLC4BGlobals.setAssertionCheck(false); - } else if (args[index].toLowerCase().equals("-wdcheck")) { - TLC4BGlobals.setWelldefinednessCheck(true); - } else if (args[index].toLowerCase().equals("-symmetry")) { - TLC4BGlobals.setSymmetryUse(true); - } else if (args[index].toLowerCase().equals("-tool")) { - TLC4BGlobals.setTool(false); - } else if (args[index].toLowerCase().equals("-tmp")) { + DefaultParser parser = new DefaultParser(); + Options options = getCommandlineOptions(); + try { + CommandLine line = parser.parse(options, args); + + String[] remainingArgs = line.getArgs(); + if (remainingArgs.length != 1) { + throw new TLC4BIOException("Main machine required!"); + } else { + mainfile = new File(remainingArgs[0]); + } + + // reset all parameters to default, then apply current args + TLC4BGlobals.resetGlobals(); + TLC4BGlobals.setVerbose(line.hasOption(VERBOSE.arg())); + TLC4BGlobals.setSilent(line.hasOption(SILENT.arg())); + TLC4BGlobals.setDeadlockCheck(!line.hasOption(NODEAD.arg())); + TLC4BGlobals.setRunTLC(!line.hasOption(NOTLC.arg())); + TLC4BGlobals.setTranslate(!line.hasOption(NOTRANSLATION.arg())); + TLC4BGlobals.setGOAL(!line.hasOption(NOGOAL.arg())); + TLC4BGlobals.setInvariant(!line.hasOption(NOINV.arg())); + TLC4BGlobals.setAssertionCheck(!line.hasOption(NOASS.arg())); + TLC4BGlobals.setWelldefinednessCheck(line.hasOption(WDCHECK.arg())); + TLC4BGlobals.setSymmetryUse(line.hasOption(SYMMETRY.arg())); + TLC4BGlobals.setCheckltl(!line.hasOption(NOLTL.arg())); + TLC4BGlobals.setForceTLCToEvalConstants(!line.hasOption(LAZYCONSTANTS.arg())); + TLC4BGlobals.setCreateTraceFile(!line.hasOption(NOTRACE.arg())); + TLC4BGlobals.setDeleteOnExit(line.hasOption(DEL.arg())); + TLC4BGlobals.setPartialInvariantEvaluation(line.hasOption(PARINVEVAL.arg())); + TLC4BGlobals.setPrintCoverage(line.hasOption(COVERAGE.arg())); + + if (line.hasOption(TMP.arg())) { buildDir = new File(System.getProperty("java.io.tmpdir")); - } else if (args[index].toLowerCase().equals("-noltl")) { - TLC4BGlobals.setCheckltl(false); - } else if (args[index].toLowerCase().equals("-lazyconstants")) { - TLC4BGlobals.setForceTLCToEvalConstants(false); - } else if (args[index].toLowerCase().equals("-testscript")) { - TLC4BGlobals.setRunTestscript(true); - } else if (args[index].toLowerCase().equals("-notrace")) { - TLC4BGlobals.setCreateTraceFile(false); - } else if (args[index].toLowerCase().equals("-del")) { - TLC4BGlobals.setDeleteOnExit(true); - } else if (args[index].toLowerCase().equals("-parinveval")) { - TLC4BGlobals.setPartialInvariantEvaluation(true); - } else if (args[index].toLowerCase().equals("-log")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: File requiered after option '-log'."); + } + if (line.hasOption(LOG.arg())) { + String logFileString = line.getOptionValue(LOG.arg()); + if (logFileString == null) { + throw new TLC4BIOException("Error: File required after option '-log'."); } - logFileString = args[index]; - - } else if (args[index].toLowerCase().equals("-maxint")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: Number requiered after option '-maxint'."); + logFile = new File(logFileString); + } + if (line.hasOption(MAXINT.arg())) { + String maxint = line.getOptionValue(MAXINT.arg()); + if (maxint == null) { + throw new TLC4BIOException("Error: Number required after option '-maxint'."); } - int maxint = Integer.parseInt(args[index]); - TLC4BGlobals.setMAX_INT(maxint); - } else if (args[index].toLowerCase().equals("-default_setsize")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: Number requiered after option '-default_setsize'."); + TLC4BGlobals.setMAX_INT(Integer.parseInt(maxint)); + } + if (line.hasOption(DEFAULT_SETSIZE.arg())) { + String deferredSetSize = line.getOptionValue(DEFAULT_SETSIZE.arg()); + if (deferredSetSize == null) { + throw new TLC4BIOException("Error: Number required after option '-default_setsize'."); } - int deferredSetSize = Integer.parseInt(args[index]); - TLC4BGlobals.setDEFERRED_SET_SIZE(deferredSetSize); + TLC4BGlobals.setDEFERRED_SET_SIZE(Integer.parseInt(deferredSetSize)); } - else if (args[index].toLowerCase().equals("-minint")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: Number requiered after option '-minint'."); + if (line.hasOption(MININT.arg())) { + String minint = line.getOptionValue(MININT.arg()); + if (minint == null) { + throw new TLC4BIOException("Error: Number required after option '-minint'."); } - int minint = Integer.parseInt(args[index]); - TLC4BGlobals.setMIN_INT(minint); - ; - } else if (args[index].toLowerCase().equals("-workers")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: Number requiered after option '-workers'."); + TLC4BGlobals.setMIN_INT(Integer.parseInt(minint)); + } + if (line.hasOption(WORKERS.arg())) { + String workers = line.getOptionValue(WORKERS.arg()); + if (workers == null) { + throw new TLC4BIOException("Error: Number required after option '-workers'."); } - int workers = Integer.parseInt(args[index]); - TLC4BGlobals.setWorkers(workers); - } else if (args[index].toLowerCase().equals("-constantssetup")) { - TLC4BGlobals.setProBconstantsSetup(true); - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: String requiered after option '-constantssetup'."); + TLC4BGlobals.setWorkers(Integer.parseInt(workers)); + } + if (line.hasOption(DFID.arg())) { + String dfid_initial_depth = line.getOptionValue(DFID.arg()); + if (dfid_initial_depth == null) { + throw new TLC4BIOException("Error: Number required after option '-dfid'."); } - constantsSetup = args[index]; - } else if (args[index].toLowerCase().equals("-ltlformula")) { - index = index + 1; - if (index == args.length) { - throw new TLC4BIOException( - "Error: LTL formula requiered after option '-ltlformula'."); + TLC4BGlobals.setDfidInitialDepth(Integer.parseInt(dfid_initial_depth)); + } + if (line.hasOption(CONSTANTSSETUP.arg())) { + TLC4BGlobals.setProBconstantsSetup(true); + constantsSetup = line.getOptionValue(CONSTANTSSETUP.arg()); + if (constantsSetup == null) { + throw new TLC4BIOException("Error: String required after option '-constantssetup'."); } - ltlFormula = args[index]; - } else if (args[index].charAt(0) == '-') { - throw new TLC4BIOException("Error: unrecognized option: " - + args[index]); - } else { - if (filename != null) { - throw new TLC4BIOException( - "Error: more than one input files: " + filename - + " and " + args[index]); + } + if (line.hasOption(LTLFORMULA.arg())) { + ltlFormula = line.getOptionValue(LTLFORMULA.arg()); + if (ltlFormula == null) { + throw new TLC4BIOException("Error: LTL formula required after option '-ltlformula'."); } - filename = args[index]; - } - index++; - } - if (filename == null) { - throw new TLC4BIOException("Main machine required!"); + if (line.hasOption(OUTPUT.arg())) { + buildDir = new File(line.getOptionValue(OUTPUT.arg())); + } + } catch (ParseException e) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("[file]", options); + throw new TLC4BIOException(e); } } - public void process(String[] args) throws IOException, BCompoundException { + private void processArgs(String[] args) { + handleParameter(args); + handleMainFileName(); - MP.print("Arguments: "); - for (int i = 0; i < args.length; i++) { - String string = args[i]; - MP.print(string); - MP.print(" "); + MP.printVerbose("Arguments: "); + for (String string : args) { + MP.printVerbose(string); + MP.printVerbose(" "); } - println(""); + printlnVerbose(""); + } - handleParameter(args); + private void translate() throws BCompoundException { + StopWatch.start(PARSING_TIME); + MP.printSilent("Parsing... "); + translator = new Translator(machineFileNameWithoutFileExtension, + mainfile, this.ltlFormula, this.constantsSetup); + StopWatch.stop(PARSING_TIME); + printlnSilent("(" + StopWatch.getRunTimeAsString(PARSING_TIME) + "ms)"); - handleMainFileName(); + StopWatch.start(TRANSLATION_TIME); + MP.printSilent("Translating... "); + translator.translate(); + this.tlaModule = translator.getModuleString(); + this.config = translator.getConfigString(); + this.tlcOutputInfo = translator.getTLCOutputInfo(); + StopWatch.stop(TRANSLATION_TIME); + printlnSilent("(" + StopWatch.getRunTimeAsString(TRANSLATION_TIME) + "ms)"); + } + + public void process(String[] args) throws IOException, BCompoundException { + processArgs(args); if (TLC4BGlobals.isTranslate()) { - StopWatch.start(PARSING_TIME); - MP.print("Parsing... "); - translator = new Translator(machineFileNameWithoutFileExtension, - mainfile, this.ltlFormula, this.constantsSetup); - StopWatch.stop(PARSING_TIME); - println("(" + StopWatch.getRunTimeAsString(PARSING_TIME) + "ms)"); - - StopWatch.start(TRANSLATION_TIME); - MP.print("Translating... "); - translator.translate(); - this.tlaModule = translator.getModuleString(); - this.config = translator.getConfigString(); - this.tlcOutputInfo = translator.getTLCOutputInfo(); - StopWatch.stop(TRANSLATION_TIME); - println("(" + StopWatch.getRunTimeAsString(TRANSLATION_TIME) - + "ms)"); + translate(); createFiles(); } - } private void handleMainFileName() { - // the following lines fix incorrect file names - filename = filename.replace("\\", File.separator); - filename = filename.replace("/", File.separator); - if (!filename.toLowerCase().endsWith(".mch") && - !filename.toLowerCase().endsWith(".sys")) { - filename = filename + ".mch"; - } - - mainfile = new File(filename); if (!mainfile.exists()) { - throw new TLC4BIOException("The file " + mainfile.getPath() - + " does not exist."); + throw new TLC4BIOException("The file " + mainfile.getPath() + " does not exist."); } try { mainfile = mainfile.getCanonicalFile(); } catch (IOException e) { - throw new TLC4BIOException("The file '" + mainfile.getPath() - + "' can not be accessed."); + throw new TLC4BIOException("The file '" + mainfile.getPath() + "' can not be accessed.", e); } machineFileNameWithoutFileExtension = mainfile.getName().substring(0, mainfile.getName().length() - 4); // deleting .mch if (buildDir == null) { - buildDir = new File(mainfile.getParentFile(), - machineFileNameWithoutFileExtension); + buildDir = new File(mainfile.getParentFile(), machineFileNameWithoutFileExtension); } } - private void createLogFile(Log log) { - if (logFileString != null) { - File logFile = new File(logFileString); - FileWriter fw; - boolean fileExists = logFile.exists(); - try { - fw = new FileWriter(logFile, true); // the true will append the - // new data - if (!fileExists) { - fw.write(log.getCSVFieldNamesLine()); - } - fw.write(log.getCSVValueLine()); - fw.close(); - println("Log file: " + logFile.getAbsolutePath()); - } catch (IOException e) { - new TLC4BIOException(e.getLocalizedMessage()); + private String getLogCsvString(TLCResults tlcResults) { + List<String> fieldNames = new ArrayList<>(); + List<String> fieldValues = new ArrayList<>(); + + fieldNames.add("Machine File"); + String machineFile = mainfile.getAbsolutePath(); + fieldValues.add(machineFile); + + fieldNames.add("TLC Model Checking Time (s)"); + double tlcModelCheckingTime = tlcResults.getModelCheckingTime(); + fieldValues.add(String.valueOf(tlcModelCheckingTime)); + + fieldNames.add("Parsing Time Of B machine (ms)"); + long parseTime = StopWatch.getRunTime(PARSING_TIME); + fieldValues.add(String.valueOf(parseTime)); + + fieldNames.add("Translation Time (ms)"); + long translationTime = StopWatch.getRunTime(TRANSLATION_TIME); + fieldValues.add(String.valueOf(translationTime)); + + fieldNames.add("Model Checking Time (ms)"); + long modelCheckingTime = StopWatch.getRunTime(MODEL_CHECKING_TIME); + fieldValues.add(String.valueOf(modelCheckingTime)); + + fieldNames.add("TLC Result"); + fieldValues.add(tlcResults.getResultString()); + + fieldNames.add("States analysed"); + fieldValues.add(Integer.toString(tlcResults.getNumberOfDistinctStates())); + + fieldNames.add("Transitions fired"); + fieldValues.add(Integer.toString(tlcResults.getNumberOfTransitions())); + + fieldNames.add("Violated Definition"); + String violatedDefinition = tlcResults.getViolatedDefinition(); + fieldValues.add(violatedDefinition != null ? violatedDefinition : ""); + + fieldNames.add("Violated Assertions"); + List<String> violatedAssertions = tlcResults.getViolatedAssertions(); + fieldValues.add(!violatedAssertions.isEmpty() ? String.join(CSV_DELIMITER, violatedAssertions) : ""); + + fieldNames.add("Operation Coverage"); + Map<String, Long> operationCount = tlcResults.getOperationCount(); + List<String> opCountString = new ArrayList<>(); + if (operationCount != null) { + operationCount.forEach((operation, count) -> opCountString.add(operation + CSV_DELIMITER + count)); + } + fieldValues.add(!opCountString.isEmpty() ? String.join(CSV_DELIMITER, opCountString) : ""); + + fieldNames.add("Trace File"); + fieldValues.add(traceFile != null ? traceFile.getAbsolutePath() : ""); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < fieldNames.size(); i++) { + sb.append(fieldNames.get(i)).append(CSV_DELIMITER).append(fieldValues.get(i)).append("\n"); + } + return sb.toString(); + } + + private void createLogFile(TLCResults results) throws IOException { + if (logFile != null) { + String logCsvString = getLogCsvString(results); + try (FileWriter fw = new FileWriter(logFile, true)) { // the true will append the new data + fw.write(logCsvString); } + println("Log file: " + logFile.getAbsolutePath()); } } - private void createFiles() { + private void createFiles() throws IOException { boolean dirCreated = buildDir.mkdir(); if (dirCreated && TLC4BGlobals.isDeleteOnExit()) { buildDir.deleteOnExit(); @@ -431,119 +477,60 @@ public class TLC4B { File moduleFile = createFile(buildDir, machineFileNameWithoutFileExtension + ".tla", tlaModule, TLC4BGlobals.isDeleteOnExit()); - if (moduleFile != null) { - println("TLA+ module '" + moduleFile.getAbsolutePath() - + "' created."); - } + println("TLA+ module '" + moduleFile.getAbsolutePath() + "' created."); File configFile = createFile(buildDir, machineFileNameWithoutFileExtension + ".cfg", config, TLC4BGlobals.isDeleteOnExit()); - if (configFile != null) { - println("Configuration file '" + configFile.getAbsolutePath() - + "' created."); - } + println("Configuration file '" + configFile.getAbsolutePath() + "' created."); createStandardModules(); } - private void createStandardModules() { - for (STANDARD_MODULES module : translator - .getStandardModuleToBeCreated()) { - createStandardModule(buildDir, module.toString()); + private void createStandardModules() throws IOException { + for (String module : translator.getStandardModuleToBeCreated()) { + createStandardModule(buildDir, module); } } - private void createStandardModule(File path, String name) { - // standard modules are copied from the standardModules folder to the - // current directory + private void createStandardModule(File path, String name) throws IOException { + // standard modules are copied from the standardModules folder to the current directory File file = new File(path, name + ".tla"); - InputStream is = null; - FileOutputStream fos = null; - try { - - try { - is = new FileInputStream("src/main/resources/standardModules/" - + name + ".tla"); - } catch (FileNotFoundException e) { - is = this - .getClass() - .getClassLoader() - .getResourceAsStream("standardModules/" + name + ".tla"); - } - - if (is == null) { - // should never happen - throw new TranslationException( - "Unable to determine the source of the standard module: " - + name); - } - - fos = new FileOutputStream(file); + InputStream resourceStream = TLC4B.class.getResourceAsStream("standardModules/" + name + ".tla"); + if (resourceStream == null) { + // should never happen + throw new TranslationException("Unable to determine the source of the standard module: " + name); + } - int read = 0; + try (InputStream is = resourceStream; OutputStream fos = new FileOutputStream(file)) { + int read; byte[] bytes = new byte[1024]; while ((read = is.read(bytes)) != -1) { fos.write(bytes, 0, read); } println("Standard module '" + file.getName() + "' created."); - } catch (IOException e) { - throw new TLC4BIOException(e.getMessage()); } finally { if (TLC4BGlobals.isDeleteOnExit() && file.exists()) { file.deleteOnExit(); } - try { - if (is != null) { - is.close(); - } - if (fos != null) { - fos.flush(); - fos.close(); - } - } catch (IOException ex) { - throw new TLC4BIOException(ex.getMessage()); - } } } - public static File createFile(File dir, String fileName, String text, - boolean deleteOnExit) { - + private static File createFile(File dir, String fileName, String text, boolean deleteOnExit) throws IOException { File file = new File(dir, fileName); boolean exists = false; try { exists = file.createNewFile(); - BufferedWriter out = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(file), "UTF-8")); - out.write(text); - out.close(); + try (Writer out = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8))) { + out.write(text); + } return file; - } catch (UnsupportedEncodingException e1) { - throw new TLC4BIOException(e1.getMessage()); - } catch (FileNotFoundException e1) { - throw new TLC4BIOException(e1.getMessage()); - } catch (IOException e) { - throw new TLC4BIOException(e.getMessage()); } finally { if (deleteOnExit && exists) { file.deleteOnExit(); } } } - - public File getBuildDir() { - return buildDir; - } - - public String getMachineFileNameWithoutFileExtension() { - return machineFileNameWithoutFileExtension; - } - - public File getMainFile(){ - return this.mainfile; - } - } diff --git a/src/main/java/de/tlc4b/TLC4BGlobals.java b/src/main/java/de/tlc4b/TLC4BGlobals.java index af3a7d49f53d46de3d1195b7bd7a507b08e9ba23..2ae19fc3df4eb8d544b9b0d3d933704fc621f4b5 100644 --- a/src/main/java/de/tlc4b/TLC4BGlobals.java +++ b/src/main/java/de/tlc4b/TLC4BGlobals.java @@ -15,25 +15,19 @@ public class TLC4BGlobals { private static boolean partialInvariantEvaluation; private static boolean useSymmetry; private static boolean printCoverage; - - private static boolean checkOnlyMainAssertions; + private static boolean verbose; + private static boolean silent; private static boolean deleteFilesOnExit; private static boolean runTLC; private static boolean translate; - private static boolean hideTLCConsoleOutput; private static boolean createTraceFile; - private static boolean testingMode; - - private static boolean cleanup; - private static boolean forceTLCToEvalConstants; private static int workers; - - private static boolean runTestscript; + private static int dfid_initial_depth; static { resetGlobals(); @@ -54,25 +48,19 @@ public class TLC4BGlobals { useSymmetry = false; printCoverage = false; forceTLCToEvalConstants = false; - checkOnlyMainAssertions = false; + verbose = false; + silent = false; proBconstantsSetup = false; - cleanup = true; - workers = 1; + dfid_initial_depth = -1; // option not selected // for debugging purposes runTLC = true; translate = true; - hideTLCConsoleOutput = false; // is mapped to TOOLIO.tool - deleteFilesOnExit = false; // if enabled: deletes all created '.tla', - // '.cfg' files on exit of the JVM. This - // includes - // the created B2TLA standard modules (e.g. - // Relation, but not Naturals etc.). - runTestscript = false; - testingMode = false; + deleteFilesOnExit = false; // if enabled: deletes all created '.tla', '.cfg' files on exit of the JVM. + // This includes the created B2TLA standard modules (e.g. Relation, but not Naturals etc.). createTraceFile = true; } @@ -84,14 +72,6 @@ public class TLC4BGlobals { TLC4BGlobals.createTraceFile = createTraceFile; } - public static boolean isRunTestscript() { - return runTestscript; - } - - public static void setRunTestscript(boolean runTestscript) { - TLC4BGlobals.runTestscript = runTestscript; - } - public static int getDEFERRED_SET_SIZE() { return DEFERRED_SET_SIZE; } @@ -132,10 +112,6 @@ public class TLC4BGlobals { return checkLTL; } - public static boolean isTool() { - return hideTLCConsoleOutput; - } - public static boolean isDeleteOnExit() { return deleteFilesOnExit; } @@ -148,20 +124,20 @@ public class TLC4BGlobals { partialInvariantEvaluation = b; } - public static void setDEFERRED_SET_SIZE(int dEFERRED_SET_SIZE) { - DEFERRED_SET_SIZE = dEFERRED_SET_SIZE; + public static void setDEFERRED_SET_SIZE(int deferredSetSize) { + TLC4BGlobals.DEFERRED_SET_SIZE = deferredSetSize; } - public static void setMAX_INT(int mAX_INT) { - MAX_INT = mAX_INT; + public static void setMAX_INT(int maxInt) { + TLC4BGlobals.MAX_INT = maxInt; } - public static void setMIN_INT(int mIN_INT) { - MIN_INT = mIN_INT; + public static void setMIN_INT(int minInt) { + TLC4BGlobals.MIN_INT = minInt; } - public static void setGOAL(boolean gOAL) { - checkGOAL = gOAL; + public static void setGOAL(boolean goal) { + TLC4BGlobals.checkGOAL = goal; } public static void setDeadlockCheck(boolean deadlockCheck) { @@ -188,10 +164,6 @@ public class TLC4BGlobals { TLC4BGlobals.checkLTL = checkltl; } - public static void setTool(boolean tool) { - TLC4BGlobals.hideTLCConsoleOutput = tool; - } - public static void setDeleteOnExit(boolean deleteOnExit) { TLC4BGlobals.deleteFilesOnExit = deleteOnExit; } @@ -204,12 +176,12 @@ public class TLC4BGlobals { return TLC4BGlobals.workers; } - public static boolean isCleanup() { - return cleanup; + public static void setDfidInitialDepth(int depth) { + TLC4BGlobals.dfid_initial_depth = depth; } - public static void setCleanup(boolean cleanup) { - TLC4BGlobals.cleanup = cleanup; + public static int getDfidInitialDepth() { + return TLC4BGlobals.dfid_initial_depth; } public static boolean isProBconstantsSetup() { @@ -220,14 +192,6 @@ public class TLC4BGlobals { TLC4BGlobals.proBconstantsSetup = proBconstantsSetup; } - public static void setTestingMode(boolean b) { - TLC4BGlobals.testingMode = b; - } - - public static boolean getTestingMode() { - return TLC4BGlobals.testingMode; - } - public static void setWelldefinednessCheck(boolean b) { TLC4BGlobals.checkWD = b; } @@ -240,8 +204,7 @@ public class TLC4BGlobals { return forceTLCToEvalConstants; } - public static void setForceTLCToEvalConstants( - boolean forceTLCToEvalConstants) { + public static void setForceTLCToEvalConstants(boolean forceTLCToEvalConstants) { TLC4BGlobals.forceTLCToEvalConstants = forceTLCToEvalConstants; } @@ -260,9 +223,20 @@ public class TLC4BGlobals { public static boolean isPrintCoverage() { return printCoverage; } - - public static boolean isCheckOnlyMainAssertions(){ - return checkOnlyMainAssertions; + + public static void setVerbose(boolean b) { + verbose = b; } + public static boolean isVerbose() { + return verbose; + } + + public static void setSilent(boolean b) { + silent = b; + } + + public static boolean isSilent() { + return silent; + } } diff --git a/src/main/java/de/tlc4b/TLC4BOption.java b/src/main/java/de/tlc4b/TLC4BOption.java new file mode 100644 index 0000000000000000000000000000000000000000..0c2292fb5cfcb978d3d7743d084a8657667ec58c --- /dev/null +++ b/src/main/java/de/tlc4b/TLC4BOption.java @@ -0,0 +1,55 @@ +package de.tlc4b; + +public enum TLC4BOption { + NODEAD("nodead", "do not look for deadlocks", null), + NOTLC("notlc", "do not run TLC", null), + NOTRANSLATION("notranslation", "proceed without machine translation", null), + NOGOAL("nogoal", "do not look for GOAL predicate", null), + NOINV("noinv", "do not look for invariant violations", null), + NOASS("noass", "do not look for ASSERTION violations", null), + WDCHECK("wdcheck", "", null), + SYMMETRY("symmetry", "", null), + TMP("tmp", "", null), + NOLTL("noltl", "no checking of LTL assertions", null), + LAZYCONSTANTS("lazyconstants", "", null), + NOTRACE("notrace", "do not generate counter example trace", null), + DEL("del", "", null), + PARINVEVAL("parinveval", "", null), + LOG("log", "write statistics to CSV file", String.class), + MAXINT("maxint", "set value of MAXINT", Integer.class), + DEFAULT_SETSIZE("default_setsize", "", Integer.class), + MININT("minint", "set value of MININT", Integer.class), + WORKERS("workers", "specify number of workers", Integer.class), + DFID("dfid", "depth-first model checking with iterative deepening, specify initial depth", Integer.class), + CONSTANTSSETUP("constantssetup", "use constants found by ProB for TLC model checking", String.class), + LTLFORMULA("ltlformula", "provide an additional LTL formula", String.class), + VERBOSE("verbose", "put TLC4B in verbose mode", null), + SILENT("silent", "put TLC4B in silent mode", null), + OUTPUT("output", "provide path for output directory", String.class), + COVERAGE("coverage", "print operation coverage", null); + + private final String arg, desc; + private final Class<?> expectsArg; + + TLC4BOption(String arg, String desc, Class<?> expectsArg) { + this.arg = arg; + this.desc = desc; + this.expectsArg = expectsArg; + } + + public String arg() { + return arg; + } + + public String cliArg() { + return "-" + arg; + } + + public String desc() { + return desc; + } + + public Class<?> expectsArg() { + return expectsArg; + } +} diff --git a/src/main/java/de/tlc4b/TLCRunner.java b/src/main/java/de/tlc4b/TLCRunner.java index 2b80c04ebdc3d8ab562d5267f289c8c0a7f9deed..d6ccdea86faace053e5851b9806f3eb42e5815fb 100644 --- a/src/main/java/de/tlc4b/TLCRunner.java +++ b/src/main/java/de/tlc4b/TLCRunner.java @@ -9,19 +9,29 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import de.tlc4b.tlc.TLCMessageListener; import de.tlc4b.util.StopWatch; +import tlc2.TLCGlobals; import util.SimpleFilenameToStream; import util.ToolIO; import tlc2.TLC; public class TLCRunner { + public static TLCMessageListener listener = null; + + public static void addTLCMessageListener(final TLCMessageListener listener) { + TLCRunner.listener = listener; + } + public static void main(String[] args) { // this method will be executed in a separate JVM System.setProperty("apple.awt.UIElement", "true"); @@ -29,15 +39,11 @@ public class TLCRunner { String path = args[0]; ToolIO.setUserDir(path); String[] parameters = new String[args.length - 1]; - for (int i = 0; i < parameters.length; i++) { - parameters[i] = args[i + 1]; - } + System.arraycopy(args, 1, parameters, 0, parameters.length); try { TLC.main(parameters); - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); + } catch (Exception e) { + throw new RuntimeException(e); } } @@ -45,27 +51,22 @@ public class TLCRunner { final String mainClass, final String[] arguments) throws IOException { - String separator = System.getProperty("file.separator"); + String separator = FileSystems.getDefault().getSeparator(); String jvm = System.getProperty("java.home") + separator + "bin" + separator + "java"; String classpath = System.getProperty("java.class.path"); - List<String> command = new ArrayList<String>(); - command.add(jvm); - command.add("-cp"); - command.add(classpath); - command.add(mainClass); + List<String> command = Arrays.asList(jvm, "-cp", classpath, mainClass); command.addAll(Arrays.asList(arguments)); ProcessBuilder processBuilder = new ProcessBuilder(command); - Process process = processBuilder.start(); - return process; + return processBuilder.start(); } public static ArrayList<String> runTLCInANewJVM(String machineName, String path) throws IOException { - ArrayList<String> list = new ArrayList<String>(); + ArrayList<String> list = new ArrayList<>(); list.add(path); list.add(machineName); if (!TLC4BGlobals.isDeadlockCheck()) { @@ -78,7 +79,7 @@ public class TLCRunner { // list.add("-coverage"); // list.add("1"); - String[] args = list.toArray(new String[list.size()]); + String[] args = list.toArray(new String[0]); final Process p = startJVM("", TLCRunner.class.getCanonicalName(), args); StreamGobbler stdOut = new StreamGobbler(p.getInputStream()); stdOut.start(); @@ -94,17 +95,29 @@ public class TLCRunner { public static void runTLC(String machineName, File path) { StopWatch.start(MODEL_CHECKING_TIME); - MP.println("--------------------------------"); + MP.printlnSilent("--------------------------------"); MP.TLCOutputStream.changeOutputStream(); ToolIO.setMode(ToolIO.SYSTEM); - ArrayList<String> list = new ArrayList<String>(); + ArrayList<String> list = new ArrayList<>(); if (!TLC4BGlobals.isDeadlockCheck()) { list.add("-deadlock"); } if (TLC4BGlobals.getWorkers() > 1) { list.add("-workers"); list.add("" + TLC4BGlobals.getWorkers()); + } else { + // When running multiple model checks from ProB2, the global state is not reset. + // Reset number of workers manually here, are there any other problematic options?! + TLCGlobals.setNumWorkers(1); + } + if (TLC4BGlobals.getDfidInitialDepth() >= 0) { + list.add("-dfid"); + list.add("" + TLC4BGlobals.getDfidInitialDepth()); + } else { + // When running multiple model checks from ProB2, the global state is not reset. + // Reset DFID manually here if not selected, are there any other problematic options?! + TLCGlobals.DFIDMax = -1; } if (TLC4BGlobals.isPrintCoverage()) { @@ -121,14 +134,16 @@ public class TLCRunner { // list.add(machineName + ".cfg"); list.add(machineName); ToolIO.setUserDir(path.getPath()); - String[] args = list.toArray(new String[list.size()]); + String[] args = list.toArray(new String[0]); TLC tlc = new TLC(); // handle parameters if (tlc.handleParameters(args)) { tlc.setResolver(new SimpleFilenameToStream()); // call the actual processing method try { + if (listener != null) listener.start(); tlc.process(); + if (listener != null) listener.finish(); } catch (Exception e) { } } @@ -142,11 +157,9 @@ public class TLCRunner { } private static void closeThreads() { - Set<Thread> threadSet = new HashSet<Thread>(Thread.getAllStackTraces() - .keySet()); - Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); - for (int i = 0; i < threadArray.length; i++) { - Thread t = threadArray[i]; + Set<Thread> threadSet = new HashSet<>(Thread.getAllStackTraces().keySet()); + Thread[] threadArray = threadSet.toArray(new Thread[0]); + for (Thread t : threadArray) { // System.out.println(t.getId()+ " "+t.getThreadGroup()); if (t.getName().equals("RMI Reaper")) { t.interrupt(); @@ -157,8 +170,8 @@ public class TLCRunner { } class StreamGobbler extends Thread { - private InputStream is; - private ArrayList<String> log; + private final InputStream is; + private final ArrayList<String> log; public ArrayList<String> getLog() { return log; @@ -166,14 +179,14 @@ class StreamGobbler extends Thread { StreamGobbler(InputStream is) { this.is = is; - this.log = new ArrayList<String>(); + this.log = new ArrayList<>(); } public void run() { try { - InputStreamReader isr = new InputStreamReader(is, "UTF-8"); + InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr); - String line = null; + String line; while ((line = br.readLine()) != null) { System.out.println("> " + line); log.add(line); diff --git a/src/main/java/de/tlc4b/Translator.java b/src/main/java/de/tlc4b/Translator.java index c177a4b3c88c0cd91eb6aaa1739b9be6afb50e44..9166b555839ac99f76f9ae530fd612cdd806a95e 100644 --- a/src/main/java/de/tlc4b/Translator.java +++ b/src/main/java/de/tlc4b/Translator.java @@ -1,9 +1,8 @@ package de.tlc4b; import java.io.File; -import java.io.IOException; -import java.util.HashSet; import java.util.Map; +import java.util.Set; import de.be4.classicalb.core.parser.BParser; import de.be4.classicalb.core.parser.analysis.prolog.RecursiveMachineLoader; @@ -21,14 +20,13 @@ import de.tlc4b.analysis.Renamer; import de.tlc4b.analysis.Typechecker; import de.tlc4b.analysis.UnsupportedConstructsFinder; import de.tlc4b.analysis.UsedStandardModules; -import de.tlc4b.analysis.UsedStandardModules.STANDARD_MODULES; import de.tlc4b.analysis.transformation.DefinitionsEliminator; import de.tlc4b.analysis.transformation.SeesEliminator; +import de.tlc4b.analysis.transformation.SequenceSubstitutionsEliminator; import de.tlc4b.analysis.transformation.SetComprehensionOptimizer; import de.tlc4b.analysis.typerestriction.TypeRestrictor; import de.tlc4b.analysis.unchangedvariables.InvariantPreservationAnalysis; import de.tlc4b.analysis.unchangedvariables.UnchangedVariablesFinder; -import de.tlc4b.exceptions.TLC4BIOException; import de.tlc4b.prettyprint.TLAPrinter; import de.tlc4b.tla.Generator; import de.tlc4b.tlc.TLCOutputInfo; @@ -36,41 +34,35 @@ import de.tlc4b.tlc.TLCOutputInfo; public class Translator { private String machineString; - private Start start; + private final Start start; private Map<String, Start> parsedMachines; private String moduleString; private String configString; private String machineName; private String ltlFormula; private PPredicate constantsSetup; - private HashSet<STANDARD_MODULES> standardModulesToBeCreated; + private Set<String> standardModulesToBeCreated; private TLCOutputInfo tlcOutputInfo; - private String translatedLTLFormula; public Translator(String machineString) throws BCompoundException { this.machineString = machineString; BParser parser = new BParser("Testing"); - start = parser.parse(machineString, false); + start = parser.parseMachine(machineString); } public Translator(String machineString, String ltlFormula) throws BCompoundException { this.machineString = machineString; this.ltlFormula = ltlFormula; BParser parser = new BParser("Testing"); - start = parser.parse(machineString, false); + start = parser.parseMachine(machineString); } - public Translator(String machineName, File machineFile, String ltlFormula, String constantSetup) - throws BCompoundException, IOException { + public Translator(String machineName, File machineFile, String ltlFormula, String constantSetup) throws BCompoundException { this.machineName = machineName; this.ltlFormula = ltlFormula; BParser parser = new BParser(machineName); - try { - start = parser.parseFile(machineFile, false); - } catch (NoClassDefFoundError e) { - throw new TLC4BIOException("Definitions file cannot be found."); - } + start = parser.parseFile(machineFile); // Definitions of definitions files are injected in the ast of the main // machine @@ -82,11 +74,11 @@ public class Translator { if (constantSetup != null) { BParser con = new BParser(); - Start start2 = null; + Start start2; try { - start2 = con.parse("#FORMULA " + constantSetup, false); + start2 = con.parseFormula(constantSetup); } catch (BCompoundException e) { - System.err.println("An error occured while parsing the constants setup predicate."); + System.err.println("An error occurred while parsing the constants setup predicate."); throw e; } @@ -96,20 +88,21 @@ public class Translator { } public void translate() { - UnsupportedConstructsFinder unsupportedConstructsFinder = new UnsupportedConstructsFinder(start); - unsupportedConstructsFinder.find(); + start.apply(new UnsupportedConstructsFinder()); // ast transformation SeesEliminator.eliminateSeesClauses(start, parsedMachines); DefinitionsEliminator.eliminateDefinitions(start); + SequenceSubstitutionsEliminator sequenceSubstitutionsEliminator = new SequenceSubstitutionsEliminator(start); + // TODO move set comprehension optimizer behind the type checker SetComprehensionOptimizer.optimizeSetComprehensions(start); MachineContext machineContext = new MachineContext(machineName, start); if (ltlFormula != null) { - machineContext.addLTLFromula(this.ltlFormula); + machineContext.addLTLFormula(this.ltlFormula); } if (this.constantsSetup != null) { machineContext.setConstantSetupPredicate(constantsSetup); @@ -117,8 +110,9 @@ public class Translator { machineContext.analyseMachine(); this.machineName = machineContext.getMachineName(); - if (machineContext.machineContainsOperations()) { - TLC4BGlobals.setPrintCoverage(true); + // ignore coverage option if machine contains no operations + if (!machineContext.machineContainsOperations()) { + TLC4BGlobals.setPrintCoverage(false); } Typechecker typechecker = new Typechecker(machineContext); @@ -149,7 +143,7 @@ public class Translator { standardModulesToBeCreated = usedModules.getStandardModulesToBeCreated(); PrimedNodesMarker primedNodesMarker = new PrimedNodesMarker(generator.getTlaModule().getOperations(), - machineContext); + machineContext, sequenceSubstitutionsEliminator.getPrimeNodes()); primedNodesMarker.start(); Renamer renamer = new Renamer(machineContext); @@ -159,7 +153,6 @@ public class Translator { printer.start(); moduleString = printer.getStringbuilder().toString(); configString = printer.getConfigString().toString(); - translatedLTLFormula = printer.geTranslatedLTLFormula(); tlcOutputInfo = new TLCOutputInfo(machineContext, renamer, typechecker, generator.getTlaModule(), generator.getConfigFile()); @@ -189,16 +182,7 @@ public class Translator { return tlcOutputInfo; } - public boolean containsUsedStandardModule(STANDARD_MODULES module) { - return standardModulesToBeCreated.contains(module); - } - - public HashSet<UsedStandardModules.STANDARD_MODULES> getStandardModuleToBeCreated() { + public Set<String> getStandardModuleToBeCreated() { return standardModulesToBeCreated; } - - public String getTranslatedLTLFormula() { - return translatedLTLFormula; - } - } diff --git a/src/main/java/de/tlc4b/analysis/ConstantsEliminator.java b/src/main/java/de/tlc4b/analysis/ConstantsEliminator.java index f6b8d10acd3a7b28f9ebebc1bf255be9ab52f688..1cc370e30f172b1583a8250499f909c35d180830 100644 --- a/src/main/java/de/tlc4b/analysis/ConstantsEliminator.java +++ b/src/main/java/de/tlc4b/analysis/ConstantsEliminator.java @@ -4,7 +4,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map.Entry; @@ -25,12 +24,11 @@ import de.be4.classicalb.core.parser.node.Node; import de.be4.classicalb.core.parser.node.PDefinition; import de.be4.classicalb.core.parser.node.PExpression; import de.be4.classicalb.core.parser.node.PPredicate; -import de.be4.classicalb.core.parser.node.TIdentifierLiteral; public class ConstantsEliminator extends DepthFirstAdapter { private final Hashtable<Node, HashSet<Node>> dependsOnIdentifierTable; - private MachineContext machineContext; + private final MachineContext machineContext; private ValuesOfIdentifierFinder valuesOfConstantsFinder; private final HashMap<Node, Integer> integerValueTable; @@ -49,8 +47,8 @@ public class ConstantsEliminator extends DepthFirstAdapter { } public ConstantsEliminator(MachineContext machineContext) { - this.dependsOnIdentifierTable = new Hashtable<Node, HashSet<Node>>(); - this.integerValueTable = new HashMap<Node, Integer>(); + this.dependsOnIdentifierTable = new Hashtable<>(); + this.integerValueTable = new HashMap<>(); this.machineContext = machineContext; } @@ -71,12 +69,12 @@ public class ConstantsEliminator extends DepthFirstAdapter { this.valuesOfConstantsFinder = new ValuesOfIdentifierFinder(); - this.valueOfIdentifier = new LinkedHashMap<Node, Node>(); + this.valueOfIdentifier = new LinkedHashMap<>(); // creating a new list of the constants, because constants will be // removed from the original list - LinkedList<Node> oldConstants = new LinkedList<Node>(machineContext.getConstantArrayList()); - if (oldConstants.size() > 0) { + LinkedList<Node> oldConstants = new LinkedList<>(machineContext.getConstantArrayList()); + if (!oldConstants.isEmpty()) { evalIdentifier(oldConstants); } @@ -85,28 +83,25 @@ public class ConstantsEliminator extends DepthFirstAdapter { } private void evalIdentifier(Collection<Node> ids) { - LinkedList<PDefinition> defsList = new LinkedList<PDefinition>(); + LinkedList<PDefinition> defsList = new LinkedList<>(); boolean newRun = true; while (newRun) { newRun = false; - Iterator<Node> itr = ids.iterator(); - while (itr.hasNext()) { - AIdentifierExpression id = (AIdentifierExpression) itr.next(); + for (Node node : ids) { + AIdentifierExpression id = (AIdentifierExpression) node; if (valueOfIdentifier.containsKey(id)) continue; - HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable - .get(id); + HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable.get(id); for (Node val : idValues) { HashSet<Node> idsInVal = dependsOnIdentifierTable.get(val); - if (idsInVal.size() == 0) { + if (idsInVal.isEmpty()) { // remove constants assignment of the properties clause removeAssignmentInPropertiesClause(val); removeConstant(id); AExpressionDefinitionDefinition def = new AExpressionDefinitionDefinition( - (TIdentifierLiteral) id.getIdentifier().get(0) - .clone(), - new LinkedList<PExpression>(), - (PExpression) val); + id.getIdentifier().get(0).clone(), + new LinkedList<>(), + (PExpression) val); machineContext.getReferences().put(def, id); machineContext.getReferences().put(id, def); defsList.add(def); @@ -120,9 +115,8 @@ public class ConstantsEliminator extends DepthFirstAdapter { } } - if (defsList.size() > 0) { - ADefinitionsMachineClause clause = machineContext - .getDefinitionMachineClause(); + if (!defsList.isEmpty()) { + ADefinitionsMachineClause clause = machineContext.getDefinitionMachineClause(); if (null == clause) { clause = new ADefinitionsMachineClause(defsList); machineContext.getAbstractMachineParseUnit() @@ -168,19 +162,14 @@ public class ConstantsEliminator extends DepthFirstAdapter { } } else if (parent instanceof APropertiesMachineClause) { machineContext.setPropertiesMachineClaus(null); - machineContext.getAbstractMachineParseUnit().getMachineClauses() - .remove(parent); + machineContext.getAbstractMachineParseUnit().getMachineClauses().remove(parent); } - } private void removeIdentifier(Collection<Node> collection, Node identifierToRemove) { - Iterator<Node> itr = collection.iterator(); - while (itr.hasNext()) { - Node id = itr.next(); - HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable - .get(id); + for (Node id : collection) { + HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable.get(id); for (Node val : idValues) { HashSet<Node> idsInVal = dependsOnIdentifierTable.get(val); idsInVal.remove(identifierToRemove); @@ -191,7 +180,7 @@ public class ConstantsEliminator extends DepthFirstAdapter { class ConstantsInTreeFinder extends DepthFirstAdapter { @Override public void defaultIn(Node node) { - dependsOnIdentifierTable.put(node, new HashSet<Node>()); + dependsOnIdentifierTable.put(node, new HashSet<>()); } @Override @@ -228,39 +217,33 @@ public class ConstantsEliminator extends DepthFirstAdapter { } class ValuesOfIdentifierFinder extends DepthFirstAdapter { - private Hashtable<Node, HashSet<Node>> valuesOfIdentifierTable; - private HashSet<Node> identifiers; + private final Hashtable<Node, HashSet<Node>> valuesOfIdentifierTable; + private final HashSet<Node> identifiers; public ValuesOfIdentifierFinder() { - valuesOfIdentifierTable = new Hashtable<Node, HashSet<Node>>(); + valuesOfIdentifierTable = new Hashtable<>(); - this.identifiers = new HashSet<Node>(); + this.identifiers = new HashSet<>(); identifiers.addAll(machineContext.getConstants().values()); identifiers.addAll(machineContext.getScalarParameter().values()); - Iterator<Node> itr = identifiers.iterator(); - while (itr.hasNext()) { - Node id = itr.next(); - valuesOfIdentifierTable.put(id, new HashSet<Node>()); + for (Node id : identifiers) { + valuesOfIdentifierTable.put(id, new HashSet<>()); } - Node constraints = machineContext.getConstraintMachineClause(); + AConstraintsMachineClause constraints = machineContext.getConstraintMachineClause(); if (constraints != null) { - analysePredicate(((AConstraintsMachineClause) constraints) - .getPredicates()); + analysePredicate(constraints.getPredicates()); } - Node properties = machineContext.getPropertiesMachineClause(); + APropertiesMachineClause properties = machineContext.getPropertiesMachineClause(); if (properties != null) { - analysePredicate(((APropertiesMachineClause) properties) - .getPredicates()); + analysePredicate(properties.getPredicates()); } - } private void analysePredicate(Node n) { if (n instanceof AEqualPredicate) { analyseEqualsPredicate((AEqualPredicate) n); - return; } else if (n instanceof AGreaterPredicate) { // analyseGreaterPredicate((AGreaterPredicate) n); } else if (n instanceof ALessEqualPredicate) { @@ -268,7 +251,6 @@ public class ConstantsEliminator extends DepthFirstAdapter { } else if (n instanceof AConjunctPredicate) { analysePredicate(((AConjunctPredicate) n).getLeft()); analysePredicate(((AConjunctPredicate) n).getRight()); - return; } } @@ -280,8 +262,7 @@ public class ConstantsEliminator extends DepthFirstAdapter { Node right_ref = machineContext.getReferences().get(right); if (left instanceof ACardExpression) { - Node ref = machineContext.getReferences().get( - ((ACardExpression) left).getExpression()); + Node ref = machineContext.getReferences().get(((ACardExpression) left).getExpression()); try { AIntegerExpression intExpr = (AIntegerExpression) right; int size = Integer.parseInt(intExpr.getLiteral().getText()); @@ -297,7 +278,7 @@ public class ConstantsEliminator extends DepthFirstAdapter { AIntegerExpression intExpr = (AIntegerExpression) left; int size = Integer.parseInt(intExpr.getLiteral().getText()); integerValueTable.put(ref, size); - } catch (ClassCastException e) { + } catch (ClassCastException ignored) { } } @@ -308,8 +289,6 @@ public class ConstantsEliminator extends DepthFirstAdapter { if (identifiers.contains(right_ref)) { valuesOfIdentifierTable.get(right_ref).add(left); } - return; - } } diff --git a/src/main/java/de/tlc4b/analysis/ConstantsEvaluator.java b/src/main/java/de/tlc4b/analysis/ConstantsEvaluator.java index 59da5145eab85be4221e88ba0b802a8c0b4607e1..f3cfbbdfef5dce2ffd5e77c98c7231b12eafcb82 100644 --- a/src/main/java/de/tlc4b/analysis/ConstantsEvaluator.java +++ b/src/main/java/de/tlc4b/analysis/ConstantsEvaluator.java @@ -5,7 +5,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.LinkedHashMap; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; @@ -31,14 +30,14 @@ import de.be4.classicalb.core.parser.node.PPredicate; * */ public class ConstantsEvaluator extends DepthFirstAdapter { - private LinkedHashMap<Node, HashSet<Node>> dependsOnIdentifierTable; - private MachineContext machineContext; - private ValuesOfIdentifierFinder valuesOfConstantsFinder; - private HashMap<Node, Integer> integerValueTable; + private final LinkedHashMap<Node, HashSet<Node>> dependsOnIdentifierTable; + private final MachineContext machineContext; + private final ValuesOfIdentifierFinder valuesOfConstantsFinder; + private final HashMap<Node, Integer> integerValueTable; private final ArrayList<Node> propertiesList; private final ArrayList<Node> invariantList; - private LinkedHashMap<Node, Node> valueOfIdentifier; + private final LinkedHashMap<Node, Node> valueOfIdentifier; public Node getValueOfConstant(Node con) { return valueOfIdentifier.get(con); @@ -65,11 +64,11 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } public ConstantsEvaluator(MachineContext machineContext) { - this.dependsOnIdentifierTable = new LinkedHashMap<Node, HashSet<Node>>(); - this.integerValueTable = new HashMap<Node, Integer>(); + this.dependsOnIdentifierTable = new LinkedHashMap<>(); + this.integerValueTable = new HashMap<>(); this.machineContext = machineContext; - this.propertiesList = new ArrayList<Node>(); - this.invariantList = new ArrayList<Node>(); + this.propertiesList = new ArrayList<>(); + this.invariantList = new ArrayList<>(); ConstantsInTreeFinder constantInTreeFinder = new ConstantsInTreeFinder(); @@ -77,21 +76,19 @@ public class ConstantsEvaluator extends DepthFirstAdapter { machineContext.getConstantsSetup().apply(constantInTreeFinder); } - APropertiesMachineClause properties = machineContext - .getPropertiesMachineClause(); + APropertiesMachineClause properties = machineContext.getPropertiesMachineClause(); if (null != properties) { properties.apply(constantInTreeFinder); } - AConstraintsMachineClause constraints = machineContext - .getConstraintMachineClause(); + AConstraintsMachineClause constraints = machineContext.getConstraintMachineClause(); if (null != constraints) { constraints.apply(constantInTreeFinder); } this.valuesOfConstantsFinder = new ValuesOfIdentifierFinder(); - this.valueOfIdentifier = new LinkedHashMap<Node, Node>(); + this.valueOfIdentifier = new LinkedHashMap<>(); evalIdentifier(machineContext.getConstants().values()); evalIdentifier(machineContext.getScalarParameter().values()); @@ -101,18 +98,15 @@ public class ConstantsEvaluator extends DepthFirstAdapter { boolean newRun = true; while (newRun) { newRun = false; - Iterator<Node> itr = ids.iterator(); - while (itr.hasNext()) { - Node id = itr.next(); + for (Node id : ids) { if (valueOfIdentifier.containsKey(id)) continue; - HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable - .get(id); + HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable.get(id); for (Node val : idValues) { HashSet<Node> idsInVal = dependsOnIdentifierTable.get(val); idsInVal.remove(id); - if (idsInVal.size() == 0) { + if (idsInVal.isEmpty()) { valueOfIdentifier.put(id, val); removeIdentifier(ids, id); newRun = true; @@ -123,13 +117,9 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } } - private void removeIdentifier(Collection<Node> collection, - Node identifierToRemove) { - Iterator<Node> itr = collection.iterator(); - while (itr.hasNext()) { - Node id = itr.next(); - HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable - .get(id); + private void removeIdentifier(Collection<Node> collection, Node identifierToRemove) { + for (Node id : collection) { + HashSet<Node> idValues = valuesOfConstantsFinder.valuesOfIdentifierTable.get(id); for (Node val : idValues) { HashSet<Node> idsInVal = dependsOnIdentifierTable.get(val); idsInVal.remove(identifierToRemove); @@ -140,7 +130,7 @@ public class ConstantsEvaluator extends DepthFirstAdapter { class ConstantsInTreeFinder extends DepthFirstAdapter { @Override public void defaultIn(Node node) { - dependsOnIdentifierTable.put(node, new HashSet<Node>()); + dependsOnIdentifierTable.put(node, new HashSet<>()); } @Override @@ -151,7 +141,6 @@ public class ConstantsEvaluator extends DepthFirstAdapter { if (parentSet != null) { parentSet.addAll(set); } - } @Override @@ -186,41 +175,33 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } class ValuesOfIdentifierFinder extends DepthFirstAdapter { - private Hashtable<Node, HashSet<Node>> valuesOfIdentifierTable; - private Hashtable<Node, ArrayList<PExpression>> rangeOfIdentifierTable; - private HashSet<Node> identifiers; + private final Hashtable<Node, HashSet<Node>> valuesOfIdentifierTable; + private final Hashtable<Node, ArrayList<PExpression>> rangeOfIdentifierTable; + private final HashSet<Node> identifiers; public ValuesOfIdentifierFinder() { - this.valuesOfIdentifierTable = new Hashtable<Node, HashSet<Node>>(); - this.rangeOfIdentifierTable = new Hashtable<Node, ArrayList<PExpression>>(); + this.valuesOfIdentifierTable = new Hashtable<>(); + this.rangeOfIdentifierTable = new Hashtable<>(); - this.identifiers = new HashSet<Node>(); + this.identifiers = new HashSet<>(); this.identifiers.addAll(machineContext.getConstants().values()); - this.identifiers.addAll(machineContext.getScalarParameter() - .values()); - - Iterator<Node> itr = identifiers.iterator(); - while (itr.hasNext()) { - Node id = itr.next(); - valuesOfIdentifierTable.put(id, new HashSet<Node>()); - rangeOfIdentifierTable.put(id, new ArrayList<PExpression>()); + this.identifiers.addAll(machineContext.getScalarParameter().values()); + + for (Node id : identifiers) { + valuesOfIdentifierTable.put(id, new HashSet<>()); + rangeOfIdentifierTable.put(id, new ArrayList<>()); } - Node constraints = machineContext.getConstraintMachineClause(); + AConstraintsMachineClause constraints = machineContext.getConstraintMachineClause(); if (constraints != null) { - analysePredicate( - ((AConstraintsMachineClause) constraints) - .getPredicates(), - false); + analysePredicate(constraints.getPredicates(), false); } if (machineContext.getConstantsSetup() != null) { if (machineContext.getConstantsSetup() instanceof ADisjunctPredicate) { - analyseConstantSetupPredicate(machineContext - .getConstantsSetup()); + analyseConstantSetupPredicate(machineContext.getConstantsSetup()); for (Node con : this.identifiers) { - ArrayList<PExpression> list = rangeOfIdentifierTable - .get(con); + ArrayList<PExpression> list = rangeOfIdentifierTable.get(con); if (list.size() == 1) { // there only one value for the constant con, hence // con remains a constant @@ -230,21 +211,17 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } else { analysePredicate(machineContext.getConstantsSetup(), true); } - } - Node properties = machineContext.getPropertiesMachineClause(); + APropertiesMachineClause properties = machineContext.getPropertiesMachineClause(); if (properties != null) { - PPredicate predicate = (PPredicate) ((APropertiesMachineClause) properties) - .getPredicates(); + PPredicate predicate = properties.getPredicates(); analysePredicate(predicate, true); - } - Node invariantClause = machineContext.getInvariantMachineClause(); + AInvariantMachineClause invariantClause = machineContext.getInvariantMachineClause(); if (invariantClause != null) { - analyseInvariantPredicate(((AInvariantMachineClause) invariantClause) - .getPredicates()); + analyseInvariantPredicate(invariantClause.getPredicates()); } } @@ -273,12 +250,10 @@ public class ConstantsEvaluator extends DepthFirstAdapter { found = true; } } - if (found == false) { - currentRange.add((PExpression) equals.getRight()); + if (!found) { + currentRange.add(equals.getRight()); } - } - } private void analyseInvariantPredicate(Node node) { @@ -303,7 +278,7 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } if (isProperties) { - propertiesList.add((PPredicate) node); + propertiesList.add(node); } } @@ -314,13 +289,11 @@ public class ConstantsEvaluator extends DepthFirstAdapter { Node right_ref = machineContext.getReferences().get(right); if (left instanceof ACardExpression) { - Node ref = machineContext.getReferences().get( - ((ACardExpression) left).getExpression()); + Node ref = machineContext.getReferences().get(((ACardExpression) left).getExpression()); if (!machineContext.getConstants().containsValue(ref)) { try { AIntegerExpression intExpr = (AIntegerExpression) right; - int size = Integer.parseInt(intExpr.getLiteral() - .getText()); + int size = Integer.parseInt(intExpr.getLiteral().getText()); integerValueTable.put(ref, size); } catch (ClassCastException e) { } @@ -328,15 +301,13 @@ public class ConstantsEvaluator extends DepthFirstAdapter { } if (right instanceof ACardExpression) { - Node ref = machineContext.getReferences().get( - ((ACardExpression) right).getExpression()); + Node ref = machineContext.getReferences().get(((ACardExpression) right).getExpression()); if (!machineContext.getConstants().containsValue(ref)) { try { AIntegerExpression intExpr = (AIntegerExpression) left; - int size = Integer.parseInt(intExpr.getLiteral() - .getText()); + int size = Integer.parseInt(intExpr.getLiteral().getText()); integerValueTable.put(ref, size); - } catch (ClassCastException e) { + } catch (ClassCastException ignored) { } } } @@ -348,8 +319,6 @@ public class ConstantsEvaluator extends DepthFirstAdapter { if (identifiers.contains(right_ref)) { valuesOfIdentifierTable.get(right_ref).add(left); } - return; - } } diff --git a/src/main/java/de/tlc4b/analysis/DefinitionsAnalyser.java b/src/main/java/de/tlc4b/analysis/DefinitionsAnalyser.java index 594dbcac5a660568bca3db70fac8acb52672b9cc..c762ff581395398062e554277218bc84f1e53268 100644 --- a/src/main/java/de/tlc4b/analysis/DefinitionsAnalyser.java +++ b/src/main/java/de/tlc4b/analysis/DefinitionsAnalyser.java @@ -22,8 +22,8 @@ import de.tlc4b.exceptions.TranslationException; */ public class DefinitionsAnalyser extends DepthFirstAdapter { - private MachineContext machineContext; - private HashMap<Node, Integer> deferredSetSizeTable; + private final MachineContext machineContext; + private final HashMap<Node, Integer> deferredSetSizeTable; public Integer getSize(Node node) { return deferredSetSizeTable.get(node); @@ -31,13 +31,12 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { public DefinitionsAnalyser(MachineContext machineContext) { this.machineContext = machineContext; - deferredSetSizeTable = new HashMap<Node, Integer>(); - HashSet<Node> deferredSets = new HashSet<Node>(machineContext - .getDeferredSets().values()); + deferredSetSizeTable = new HashMap<>(); + HashSet<Node> deferredSets = new HashSet<>(machineContext.getDeferredSets().values()); findDefaultSizesInDefinitions(); - if (deferredSets.size() == 0) + if (deferredSets.isEmpty()) return; Set<String> strings = machineContext.getDeferredSets().keySet(); @@ -85,9 +84,7 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { int value = Integer.parseInt(sizeExpr.getLiteral().getText()); TLC4BGlobals.setDEFERRED_SET_SIZE(value); } catch (ClassCastException e) { - throw new TranslationException( - "Unable to determine the default set size from definition SET_PREF_DEFAULT_SETSIZE: " - + node.getEndPos()); + throw new TranslationException("Unable to determine the default set size from definition SET_PREF_DEFAULT_SETSIZE: " + node.getEndPos(), e); } } @@ -99,9 +96,7 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { int value = Integer.parseInt(sizeExpr.getLiteral().getText()); TLC4BGlobals.setMAX_INT(value); } catch (ClassCastException e) { - throw new TranslationException( - "Unable to determine MAXINT from definition SET_PREF_MAXINT: " - + node.getEndPos()); + throw new TranslationException("Unable to determine MAXINT from definition SET_PREF_MAXINT: " + node.getEndPos(), e); } } @@ -109,8 +104,8 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { if (null != node) { try { AExpressionDefinitionDefinition d = (AExpressionDefinitionDefinition) node; - AIntegerExpression sizeExpr = null; - Integer value = null; + AIntegerExpression sizeExpr; + int value; if (d.getRhs() instanceof AUnaryMinusExpression) { AUnaryMinusExpression minus = (AUnaryMinusExpression) d .getRhs(); @@ -122,8 +117,7 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { } TLC4BGlobals.setMIN_INT(value); } catch (ClassCastException e) { - throw new TranslationException( - "Unable to determine the MININT from definition SET_PREF_MININT: " + node.getEndPos()); + throw new TranslationException("Unable to determine the MININT from definition SET_PREF_MININT: " + node.getEndPos(), e); } } } @@ -146,7 +140,6 @@ public class DefinitionsAnalyser extends DepthFirstAdapter { String intString = integer.getLiteral().getText(); deferredSetSizeTable.put(ref_node, Integer.parseInt(intString)); } catch (ClassCastException e) { - return; } } diff --git a/src/main/java/de/tlc4b/analysis/DefinitionsSorter.java b/src/main/java/de/tlc4b/analysis/DefinitionsSorter.java index 61f051101ce06ba8ec08214a6978bc29ea8fdaaf..7aaa6dd8484eb2994e78a3aa2d9d048d681ead09 100644 --- a/src/main/java/de/tlc4b/analysis/DefinitionsSorter.java +++ b/src/main/java/de/tlc4b/analysis/DefinitionsSorter.java @@ -3,7 +3,6 @@ package de.tlc4b.analysis; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; import de.be4.classicalb.core.parser.node.ADefinitionExpression; @@ -22,11 +21,11 @@ import de.be4.classicalb.core.parser.node.PDefinition; */ public class DefinitionsSorter extends DepthFirstAdapter { - private MachineContext machineContext; - private Hashtable<Node, HashSet<Node>> dependenciesTable; + private final MachineContext machineContext; + private final Hashtable<Node, HashSet<Node>> dependenciesTable; private HashSet<Node> current; - private ArrayList<PDefinition> allDefinitions; + private final ArrayList<PDefinition> allDefinitions; public ArrayList<PDefinition> getAllDefinitions() { return allDefinitions; @@ -35,28 +34,26 @@ public class DefinitionsSorter extends DepthFirstAdapter { public DefinitionsSorter(MachineContext machineContext, ArrayList<PDefinition> allDefinitions) { this.machineContext = machineContext; - dependenciesTable = new Hashtable<Node, HashSet<Node>>(); + dependenciesTable = new Hashtable<>(); for (PDefinition def : allDefinitions) { def.apply(this); } - this.allDefinitions = sort(new ArrayList<PDefinition>(allDefinitions)); + this.allDefinitions = sort(new ArrayList<>(allDefinitions)); } private ArrayList<PDefinition> sort(ArrayList<PDefinition> list) { - ArrayList<PDefinition> result = new ArrayList<PDefinition>(); + ArrayList<PDefinition> result = new ArrayList<>(); boolean newRun = true; while (newRun) { newRun = false; - Iterator<PDefinition> itr = list.iterator(); - while (itr.hasNext()) { - PDefinition def = itr.next(); + for (PDefinition def : list) { if (result.contains(def)) continue; HashSet<Node> set = dependenciesTable.get(def); - if (set.size() == 0) { + if (set.isEmpty()) { newRun = true; result.add(def); @@ -83,15 +80,14 @@ public class DefinitionsSorter extends DepthFirstAdapter { } private void removeDef(Node def) { - Iterator<HashSet<Node>> itr = dependenciesTable.values().iterator(); - while (itr.hasNext()) { - itr.next().remove(def); + for (HashSet<Node> nodes : dependenciesTable.values()) { + nodes.remove(def); } } public void inAExpressionDefinitionDefinition( AExpressionDefinitionDefinition node) { - current = new HashSet<Node>(); + current = new HashSet<>(); } public void outAExpressionDefinitionDefinition( @@ -102,7 +98,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { public void inAPredicateDefinitionDefinition( APredicateDefinitionDefinition node) { - current = new HashSet<Node>(); + current = new HashSet<>(); } public void outAPredicateDefinitionDefinition( @@ -113,7 +109,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { public void inASubstitutionDefinitionDefinition( ASubstitutionDefinitionDefinition node) { - current = new HashSet<Node>(); + current = new HashSet<>(); } public void outASubstitutionDefinitionDefinition( diff --git a/src/main/java/de/tlc4b/analysis/MachineContext.java b/src/main/java/de/tlc4b/analysis/MachineContext.java index 3bcadcdd318d593c6efad2ce7228477382440c63..92de4664c54c76feee80744c02a2d67c0e9c9d49 100644 --- a/src/main/java/de/tlc4b/analysis/MachineContext.java +++ b/src/main/java/de/tlc4b/analysis/MachineContext.java @@ -1,79 +1,24 @@ package de.tlc4b.analysis; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; +import java.util.*; import java.util.Map.Entry; +import java.util.stream.Collectors; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; -import de.be4.classicalb.core.parser.node.AAbstractConstantsMachineClause; -import de.be4.classicalb.core.parser.node.AAbstractMachineParseUnit; -import de.be4.classicalb.core.parser.node.AAnySubstitution; -import de.be4.classicalb.core.parser.node.AAssertionsMachineClause; -import de.be4.classicalb.core.parser.node.AAssignSubstitution; -import de.be4.classicalb.core.parser.node.AComprehensionSetExpression; -import de.be4.classicalb.core.parser.node.AConcreteVariablesMachineClause; -import de.be4.classicalb.core.parser.node.AConstantsMachineClause; -import de.be4.classicalb.core.parser.node.AConstraintsMachineClause; -import de.be4.classicalb.core.parser.node.ADeferredSetSet; -import de.be4.classicalb.core.parser.node.ADefinitionExpression; -import de.be4.classicalb.core.parser.node.ADefinitionPredicate; -import de.be4.classicalb.core.parser.node.ADefinitionSubstitution; -import de.be4.classicalb.core.parser.node.ADefinitionsMachineClause; -import de.be4.classicalb.core.parser.node.AEnumeratedSetSet; -import de.be4.classicalb.core.parser.node.AEventBComprehensionSetExpression; -import de.be4.classicalb.core.parser.node.AExistsPredicate; -import de.be4.classicalb.core.parser.node.AExpressionDefinitionDefinition; -import de.be4.classicalb.core.parser.node.AForallPredicate; -import de.be4.classicalb.core.parser.node.AFunctionExpression; -import de.be4.classicalb.core.parser.node.AGeneralProductExpression; -import de.be4.classicalb.core.parser.node.AGeneralSumExpression; -import de.be4.classicalb.core.parser.node.AIdentifierExpression; -import de.be4.classicalb.core.parser.node.AInitialisationMachineClause; -import de.be4.classicalb.core.parser.node.AInvariantMachineClause; -import de.be4.classicalb.core.parser.node.ALambdaExpression; -import de.be4.classicalb.core.parser.node.ALetSubstitution; -import de.be4.classicalb.core.parser.node.AMachineHeader; -import de.be4.classicalb.core.parser.node.AMachineReferenceNoParams; -import de.be4.classicalb.core.parser.node.AOpSubstitution; -import de.be4.classicalb.core.parser.node.AOperation; -import de.be4.classicalb.core.parser.node.AOperationsMachineClause; -import de.be4.classicalb.core.parser.node.APredicateDefinitionDefinition; -import de.be4.classicalb.core.parser.node.APredicateParseUnit; -import de.be4.classicalb.core.parser.node.APrimedIdentifierExpression; -import de.be4.classicalb.core.parser.node.APropertiesMachineClause; -import de.be4.classicalb.core.parser.node.AQuantifiedIntersectionExpression; -import de.be4.classicalb.core.parser.node.AQuantifiedUnionExpression; -import de.be4.classicalb.core.parser.node.ARecEntry; -import de.be4.classicalb.core.parser.node.ARecordFieldExpression; -import de.be4.classicalb.core.parser.node.ASeesMachineClause; -import de.be4.classicalb.core.parser.node.ASetsContextClause; -import de.be4.classicalb.core.parser.node.ASubstitutionDefinitionDefinition; -import de.be4.classicalb.core.parser.node.AVariablesMachineClause; -import de.be4.classicalb.core.parser.node.Node; -import de.be4.classicalb.core.parser.node.PDefinition; -import de.be4.classicalb.core.parser.node.PExpression; -import de.be4.classicalb.core.parser.node.PMachineClause; -import de.be4.classicalb.core.parser.node.PMachineHeader; -import de.be4.classicalb.core.parser.node.PMachineReferenceNoParams; -import de.be4.classicalb.core.parser.node.POperation; -import de.be4.classicalb.core.parser.node.PPredicate; -import de.be4.classicalb.core.parser.node.PSet; -import de.be4.classicalb.core.parser.node.Start; -import de.be4.classicalb.core.parser.node.TIdentifierLiteral; +import de.be4.classicalb.core.parser.node.*; import de.be4.classicalb.core.parser.util.Utils; import de.tlc4b.MP; import de.tlc4b.TLC4BGlobals; import de.tlc4b.analysis.transformation.DefinitionsSorter; import de.tlc4b.analysis.transformation.MachineClauseSorter; +import de.tlc4b.exceptions.NotSupportedException; import de.tlc4b.exceptions.ScopeException; import de.tlc4b.ltl.LTLBPredicate; import de.tlc4b.ltl.LTLFormulaVisitor; +import static de.tlc4b.util.UtilMethods.getIdentifierExpression; +import static de.tlc4b.util.UtilMethods.getOperation; + public class MachineContext extends DepthFirstAdapter { private String machineName; @@ -104,7 +49,7 @@ public class MachineContext extends DepthFirstAdapter { private AInvariantMachineClause invariantMachineClause; private AInitialisationMachineClause initialisationMachineClause; private AOperationsMachineClause operationMachineClause; - private AAssertionsMachineClause assertiondMachineClause; + private AAssertionsMachineClause assertionsMachineClause; private ArrayList<LinkedHashMap<String, Node>> contextTable; @@ -113,19 +58,19 @@ public class MachineContext extends DepthFirstAdapter { public MachineContext(final String machineName, final Start start) { this.start = start; this.machineName = machineName; - this.referencesTable = new Hashtable<Node, Node>(); - this.ltlVisitors = new ArrayList<LTLFormulaVisitor>(); - - this.machineSetParameter = new LinkedHashMap<String, Node>(); - this.machineScalarParameter = new LinkedHashMap<String, Node>(); - - this.deferredSets = new LinkedHashMap<String, Node>(); - this.enumeratedSets = new LinkedHashMap<String, Node>(); - this.enumValues = new LinkedHashMap<String, Node>(); - this.constants = new LinkedHashMap<String, Node>(); - this.variables = new LinkedHashMap<String, Node>(); - this.definitions = new LinkedHashMap<String, Node>(); - this.operations = new LinkedHashMap<String, Node>(); + this.referencesTable = new Hashtable<>(); + this.ltlVisitors = new ArrayList<>(); + + this.machineSetParameter = new LinkedHashMap<>(); + this.machineScalarParameter = new LinkedHashMap<>(); + + this.deferredSets = new LinkedHashMap<>(); + this.enumeratedSets = new LinkedHashMap<>(); + this.enumValues = new LinkedHashMap<>(); + this.constants = new LinkedHashMap<>(); + this.variables = new LinkedHashMap<>(); + this.definitions = new LinkedHashMap<>(); + this.operations = new LinkedHashMap<>(); this.seenMachines = new LinkedHashMap<>(); } @@ -135,7 +80,7 @@ public class MachineContext extends DepthFirstAdapter { checkLTLFormulas(); } - public void addLTLFromula(final String ltlFormula) { + public void addLTLFormula(final String ltlFormula) { LTLFormulaVisitor ltlVisitor = new LTLFormulaVisitor("ltl", this); ltlVisitor.parseLTLString(ltlFormula); this.ltlVisitors.add(ltlVisitor); @@ -149,10 +94,9 @@ public class MachineContext extends DepthFirstAdapter { if (constantsSetupPredicate == null) { return; } - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); + for (MachineContext s : list) { contextTable.add(s.getDeferredSets()); contextTable.add(s.getEnumeratedSets()); contextTable.add(s.getEnumValues()); @@ -167,9 +111,8 @@ public class MachineContext extends DepthFirstAdapter { ltlVisitors.get(0).start(); return; } - ArrayList<LTLFormulaVisitor> formulasNotSupportedByTLC = new ArrayList<LTLFormulaVisitor>(); - for (int i = 0; i < ltlVisitors.size(); i++) { - LTLFormulaVisitor visitor = ltlVisitors.get(i); + ArrayList<LTLFormulaVisitor> formulasNotSupportedByTLC = new ArrayList<>(); + for (LTLFormulaVisitor visitor : ltlVisitors) { try { visitor.start(); } catch (ScopeException e) { @@ -181,7 +124,7 @@ public class MachineContext extends DepthFirstAdapter { } public void checkLTLBPredicate(LTLBPredicate ltlbPredicate) { - contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + contextTable = new ArrayList<>(); contextTable.add(getDeferredSets()); contextTable.add(getEnumeratedSets()); contextTable.add(getEnumValues()); @@ -190,9 +133,8 @@ public class MachineContext extends DepthFirstAdapter { contextTable.add(getDefinitions()); LinkedHashMap<String, Node> identifierHashTable = ltlbPredicate.getIdentifierList(); - if (identifierHashTable.size() > 0) { - LinkedHashMap<String, Node> currentContext = new LinkedHashMap<String, Node>(); - currentContext.putAll(identifierHashTable); + if (!identifierHashTable.isEmpty()) { + LinkedHashMap<String, Node> currentContext = new LinkedHashMap<>(identifierHashTable); contextTable.add(currentContext); } ltlbPredicate.getBFormula().apply(this); @@ -236,11 +178,11 @@ public class MachineContext extends DepthFirstAdapter { public void caseAMachineHeader(AMachineHeader node) { this.header = node; if (machineName == null) { - List<TIdentifierLiteral> nameList = new ArrayList<TIdentifierLiteral>(node.getName()); + List<TIdentifierLiteral> nameList = new ArrayList<>(node.getName()); this.machineName = Utils.getTIdentifierListAsString(nameList); } - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { AIdentifierExpression p = (AIdentifierExpression) e; String name = Utils.getTIdentifierListAsString(p.getIdentifier()); @@ -274,7 +216,7 @@ public class MachineContext extends DepthFirstAdapter { * definitions can depend on each other. First all definitions are added * to the definitions context table. Then all definitions are visited. */ - Collection<PDefinition> definitionsToRemove = new HashSet<PDefinition>(); + Collection<PDefinition> definitionsToRemove = new HashSet<>(); for (PDefinition e : copy) { if (e instanceof AExpressionDefinitionDefinition) { @@ -290,11 +232,11 @@ public class MachineContext extends DepthFirstAdapter { } else if (name.startsWith("ANIMATION_")) { definitionsToRemove.add(def); } - evalDefinitionName(((AExpressionDefinitionDefinition) e).getName().getText().toString(), e); + evalDefinitionName(((AExpressionDefinitionDefinition) e).getName().getText(), e); } else if (e instanceof APredicateDefinitionDefinition) { - evalDefinitionName(((APredicateDefinitionDefinition) e).getName().getText().toString(), e); + evalDefinitionName(((APredicateDefinitionDefinition) e).getName().getText(), e); } else if (e instanceof ASubstitutionDefinitionDefinition) { - evalDefinitionName(((ASubstitutionDefinitionDefinition) e).getName().getText().toString(), e); + evalDefinitionName(((ASubstitutionDefinitionDefinition) e).getName().getText(), e); } } /* @@ -302,10 +244,9 @@ public class MachineContext extends DepthFirstAdapter { * formulas are stored in the Arraylist {@value #ltlVisitors}. */ copy.removeAll(definitionsToRemove); - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); + for (MachineContext s : list) { contextTable.add(s.getDeferredSets()); contextTable.add(s.getEnumeratedSets()); contextTable.add(s.getEnumValues()); @@ -326,18 +267,18 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAExpressionDefinitionDefinition(AExpressionDefinitionDefinition node) { - visitBDefinition(node, node.getName().getText().toString(), node.getParameters(), node.getRhs()); + visitBDefinition(node, node.getName().getText(), node.getParameters(), node.getRhs()); } @Override public void caseAPredicateDefinitionDefinition(APredicateDefinitionDefinition node) { - visitBDefinition(node, node.getName().getText().toString(), node.getParameters(), node.getRhs()); + visitBDefinition(node, node.getName().getText(), node.getParameters(), node.getRhs()); } /* d == x := 1 */ @Override public void caseASubstitutionDefinitionDefinition(ASubstitutionDefinitionDefinition node) { - visitBDefinition(node, node.getName().getText().toString(), node.getParameters(), node.getRhs()); + visitBDefinition(node, node.getName().getText(), node.getParameters(), node.getRhs()); } @@ -345,7 +286,7 @@ public class MachineContext extends DepthFirstAdapter { if (!this.definitions.containsValue(node)) { return; } - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -355,17 +296,17 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseADefinitionExpression(ADefinitionExpression node) { - visitBDefinitionCall(node, node.getDefLiteral().getText().toString(), node.getParameters()); + visitBDefinitionCall(node, node.getDefLiteral().getText(), node.getParameters()); } @Override public void caseADefinitionPredicate(ADefinitionPredicate node) { - visitBDefinitionCall(node, node.getDefLiteral().getText().toString(), node.getParameters()); + visitBDefinitionCall(node, node.getDefLiteral().getText(), node.getParameters()); } @Override public void caseADefinitionSubstitution(ADefinitionSubstitution node) { - visitBDefinitionCall(node, node.getDefLiteral().getText().toString(), node.getParameters()); + visitBDefinitionCall(node, node.getDefLiteral().getText(), node.getParameters()); } private void visitBDefinitionCall(Node node, String name, List<PExpression> copy) { @@ -379,7 +320,7 @@ public class MachineContext extends DepthFirstAdapter { return; } } - throw new ScopeException("Unkown definition: '" + name + "' at position: " + node.getStartPos()); + throw new ScopeException("Unknown definition: '" + name + "' at position: " + node.getStartPos()); } @Override @@ -392,7 +333,7 @@ public class MachineContext extends DepthFirstAdapter { try { identifierAlreadyExists(name); } catch (ScopeException e2) { - throw new ScopeException("Machine '" + name + "' is seen twice."); + throw new ScopeException("Machine '" + name + "' is seen twice.", e2); } seenMachines.put(name, p); } @@ -401,7 +342,7 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseASetsContextClause(ASetsContextClause node) { this.setsMachineClause = node; - List<PSet> copy = new ArrayList<PSet>(node.getSet()); + List<PSet> copy = new ArrayList<>(node.getSet()); for (PSet e : copy) { e.apply(this); } @@ -409,7 +350,7 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseADeferredSetSet(ADeferredSetSet node) { - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>(node.getIdentifier()); + List<TIdentifierLiteral> copy = new ArrayList<>(node.getIdentifier()); String name = Utils.getTIdentifierListAsString(copy); exist(node.getIdentifier()); deferredSets.put(name, node); @@ -418,63 +359,42 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAEnumeratedSetSet(AEnumeratedSetSet node) { { - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>(node.getIdentifier()); + List<TIdentifierLiteral> copy = new ArrayList<>(node.getIdentifier()); String name = Utils.getTIdentifierListAsString(copy); exist(node.getIdentifier()); enumeratedSets.put(name, node); } - List<PExpression> copy = new ArrayList<PExpression>(node.getElements()); - for (PExpression e : copy) { - AIdentifierExpression v = (AIdentifierExpression) e; - String name = Utils.getTIdentifierListAsString(v.getIdentifier()); - exist(v.getIdentifier()); - enumValues.put(name, v); - } + extractIdentifierExpressions(new ArrayList<>(node.getElements()), enumValues); } @Override public void caseAConstantsMachineClause(AConstantsMachineClause node) { hasConstants = true; - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression c = (AIdentifierExpression) e; - String name = Utils.getTIdentifierListAsString(c.getIdentifier()); - exist(c.getIdentifier()); - constants.put(name, c); - } + extractIdentifierExpressions(new ArrayList<>(node.getIdentifiers()), constants); } @Override public void caseAAbstractConstantsMachineClause(AAbstractConstantsMachineClause node) { hasConstants = true; - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression c = (AIdentifierExpression) e; - String name = Utils.getTIdentifierListAsString(c.getIdentifier()); - exist(c.getIdentifier()); - constants.put(name, c); - } + extractIdentifierExpressions(new ArrayList<>(node.getIdentifiers()), constants); } @Override public void caseAVariablesMachineClause(AVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression v = (AIdentifierExpression) e; - String name = Utils.getTIdentifierListAsString(v.getIdentifier()); - exist(v.getIdentifier()); - variables.put(name, v); - } + extractIdentifierExpressions(new ArrayList<>(node.getIdentifiers()), variables); } @Override public void caseAConcreteVariablesMachineClause(AConcreteVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + extractIdentifierExpressions(new ArrayList<>(node.getIdentifiers()), variables); + } + + private void extractIdentifierExpressions(List<PExpression> copy, Map<String, Node> addToMap) { for (PExpression e : copy) { - AIdentifierExpression v = (AIdentifierExpression) e; - String name = Utils.getTIdentifierListAsString(v.getIdentifier()); - exist(v.getIdentifier()); - variables.put(name, v); + AIdentifierExpression identifier = getIdentifierExpression(e); + String name = Utils.getTIdentifierListAsString(identifier.getIdentifier()); + exist(identifier.getIdentifier()); + addToMap.put(name, identifier); } } @@ -498,7 +418,7 @@ public class MachineContext extends DepthFirstAdapter { return; } } - throw new ScopeException("Unkown Identifier: '" + name + "' at position: " + node.getStartPos()); + throw new ScopeException("Unknown Identifier: '" + name + "' at position: " + node.getStartPos()); } @Override @@ -511,11 +431,11 @@ public class MachineContext extends DepthFirstAdapter { return; } } - throw new ScopeException("Unkown Identifier: '" + name + "' at position: " + node.getStartPos()); + throw new ScopeException("Unknown Identifier: '" + name + "' at position: " + node.getStartPos()); } private ArrayList<MachineContext> lookupReferencedMachines() { - ArrayList<MachineContext> list = new ArrayList<MachineContext>(); + ArrayList<MachineContext> list = new ArrayList<>(); list.add(this); return list; } @@ -524,7 +444,7 @@ public class MachineContext extends DepthFirstAdapter { public void caseAConstraintsMachineClause(AConstraintsMachineClause node) { this.constraintMachineClause = node; - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); this.contextTable.add(this.machineScalarParameter); this.contextTable.add(this.machineSetParameter); if (node.getPredicates() != null) { @@ -536,14 +456,13 @@ public class MachineContext extends DepthFirstAdapter { public void caseAPropertiesMachineClause(APropertiesMachineClause node) { this.propertiesMachineClause = node; hasConstants = true; - /** + /* * check identifier scope in properties clauses */ - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); + for (MachineContext s : list) { contextTable.add(s.getDeferredSets()); contextTable.add(s.getEnumeratedSets()); contextTable.add(s.getEnumValues()); @@ -559,12 +478,11 @@ public class MachineContext extends DepthFirstAdapter { public void caseAInvariantMachineClause(AInvariantMachineClause node) { this.invariantMachineClause = node; - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); - this.contextTable.add(s.getSetParamter()); + for (MachineContext s : list) { + this.contextTable.add(s.getSetParameter()); this.contextTable.add(s.getScalarParameter()); this.contextTable.add(s.getDeferredSets()); this.contextTable.add(s.getEnumeratedSets()); @@ -578,13 +496,12 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAAssertionsMachineClause(AAssertionsMachineClause node) { - this.assertiondMachineClause = node; + this.assertionsMachineClause = node; - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); - this.contextTable.add(s.getSetParamter()); + for (MachineContext s : list) { + this.contextTable.add(s.getSetParameter()); this.contextTable.add(s.getScalarParameter()); this.contextTable.add(s.getDeferredSets()); this.contextTable.add(s.getEnumeratedSets()); @@ -594,7 +511,7 @@ public class MachineContext extends DepthFirstAdapter { this.contextTable.add(s.getVariables()); } - List<PPredicate> copy = new ArrayList<PPredicate>(node.getPredicates()); + List<PPredicate> copy = new ArrayList<>(node.getPredicates()); for (PPredicate e : copy) { e.apply(this); } @@ -604,13 +521,11 @@ public class MachineContext extends DepthFirstAdapter { public void caseAInitialisationMachineClause(AInitialisationMachineClause node) { this.initialisationMachineClause = node; - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); - - this.contextTable.add(s.getSetParamter()); + for (MachineContext s : list) { + this.contextTable.add(s.getSetParameter()); this.contextTable.add(s.getScalarParameter()); this.contextTable.add(s.getDeferredSets()); this.contextTable.add(s.getEnumeratedSets()); @@ -627,11 +542,10 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAOperationsMachineClause(AOperationsMachineClause node) { this.operationMachineClause = node; - this.contextTable = new ArrayList<LinkedHashMap<String, Node>>(); + this.contextTable = new ArrayList<>(); ArrayList<MachineContext> list = lookupReferencedMachines(); - for (int i = 0; i < list.size(); i++) { - MachineContext s = list.get(i); - this.contextTable.add(s.getSetParamter()); + for (MachineContext s : list) { + this.contextTable.add(s.getSetParameter()); this.contextTable.add(s.getScalarParameter()); this.contextTable.add(s.getDeferredSets()); this.contextTable.add(s.getEnumeratedSets()); @@ -640,13 +554,13 @@ public class MachineContext extends DepthFirstAdapter { this.contextTable.add(s.getDefinitions()); this.contextTable.add(s.getVariables()); } - List<POperation> copy = new ArrayList<POperation>(node.getOperations()); + List<POperation> copy = new ArrayList<>(node.getOperations()); // first collect all operations for (POperation e : copy) { - AOperation op = (AOperation) e; + AOperation op = getOperation(e); String name = Utils.getTIdentifierListAsString(op.getOpName()); // existString(name); - if (operations.keySet().contains(name)) { + if (operations.containsKey(name)) { throw new ScopeException(String.format("Duplicate operation: '%s'", name)); } operations.put(name, op); @@ -659,9 +573,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAOperation(AOperation node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getReturnValues()); + List<PExpression> copy = new ArrayList<>(node.getReturnValues()); for (PExpression e : copy) { AIdentifierExpression id = (AIdentifierExpression) e; exist(id.getIdentifier()); @@ -670,7 +584,7 @@ public class MachineContext extends DepthFirstAdapter { } { - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { AIdentifierExpression id = (AIdentifierExpression) e; exist(id.getIdentifier()); @@ -687,8 +601,8 @@ public class MachineContext extends DepthFirstAdapter { public void caseAAssignSubstitution(AAssignSubstitution node) { ArrayList<LinkedHashMap<String, Node>> temp = contextTable; { - List<PExpression> copy = new ArrayList<PExpression>(node.getLhsExpression()); - ArrayList<LinkedHashMap<String, Node>> varTable = new ArrayList<LinkedHashMap<String, Node>>(); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); + ArrayList<LinkedHashMap<String, Node>> varTable = new ArrayList<>(); varTable.add(variables); for (PExpression e : copy) { if (e instanceof AFunctionExpression) { @@ -708,7 +622,7 @@ public class MachineContext extends DepthFirstAdapter { } { contextTable = temp; - List<PExpression> copy = new ArrayList<PExpression>(node.getRhsExpressions()); + List<PExpression> copy = new ArrayList<>(node.getRhsExpressions()); for (PExpression e : copy) { e.apply(this); } @@ -717,8 +631,8 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseALetSubstitution(ALetSubstitution node) { - contextTable.add(new LinkedHashMap<String, Node>()); - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + contextTable.add(new LinkedHashMap<>()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -728,8 +642,8 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAAnySubstitution(AAnySubstitution node) { - contextTable.add(new LinkedHashMap<String, Node>()); - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + contextTable.add(new LinkedHashMap<>()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -738,19 +652,22 @@ public class MachineContext extends DepthFirstAdapter { } @Override - public void caseAOpSubstitution(AOpSubstitution node) { - if (node.getName() != null) { - AIdentifierExpression op = (AIdentifierExpression) node.getName(); - String name = Utils.getTIdentifierListAsString(op.getIdentifier()); - Node o = operations.get(name); - if (o != null) { - this.referencesTable.put(op, o); - } else { - throw new ScopeException("Unknown operation '" + name + "'"); - } + public void caseAOperationCallSubstitution(AOperationCallSubstitution node) { + if (!node.getResultIdentifiers().isEmpty()) { + throw new NotSupportedException("Operation calls with return values are not supported."); + } + String name = Utils.getTIdentifierListAsString(node.getOperation()); + Node o = operations.get(name); + if (o != null) { + AIdentifierExpression op = new AIdentifierExpression(node.getOperation().stream() + .map(TIdentifierLiteral::clone) + .collect(Collectors.toList())); + this.referencesTable.put(op, o); + } else { + throw new ScopeException("Unknown operation '" + name + "'"); } { - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { e.apply(this); } @@ -759,9 +676,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAForallPredicate(AForallPredicate node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -774,9 +691,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAExistsPredicate(AExistsPredicate node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -789,9 +706,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseALambdaExpression(ALambdaExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -803,9 +720,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAComprehensionSetExpression(AComprehensionSetExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -816,9 +733,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAEventBComprehensionSetExpression(AEventBComprehensionSetExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -831,9 +748,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -849,9 +766,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAQuantifiedIntersectionExpression(AQuantifiedIntersectionExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -867,9 +784,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAGeneralProductExpression(AGeneralProductExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -885,9 +802,9 @@ public class MachineContext extends DepthFirstAdapter { @Override public void caseAGeneralSumExpression(AGeneralSumExpression node) { - contextTable.add(new LinkedHashMap<String, Node>()); + contextTable.add(new LinkedHashMap<>()); { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { putLocalVariableIntoCurrentScope((AIdentifierExpression) e); } @@ -901,16 +818,6 @@ public class MachineContext extends DepthFirstAdapter { contextTable.remove(contextTable.size() - 1); } - @Override - public void caseARecEntry(ARecEntry node) { - node.getValue().apply(this); - } - - @Override - public void caseARecordFieldExpression(ARecordFieldExpression node) { - node.getRecord().apply(this); - } - public String getMachineName() { return machineName; } @@ -923,12 +830,12 @@ public class MachineContext extends DepthFirstAdapter { return start; } - public LinkedHashMap<String, Node> getSetParamter() { + public LinkedHashMap<String, Node> getSetParameter() { return new LinkedHashMap<>(machineSetParameter); } public ArrayList<Node> getConstantArrayList() { - ArrayList<Node> list = new ArrayList<Node>(); + ArrayList<Node> list = new ArrayList<>(); for (Entry<String, Node> entry : constants.entrySet()) { list.add(entry.getValue()); } @@ -1008,7 +915,7 @@ public class MachineContext extends DepthFirstAdapter { } public AAssertionsMachineClause getAssertionMachineClause() { - return assertiondMachineClause; + return assertionsMachineClause; } public void setPropertiesMachineClaus(APropertiesMachineClause propertiesMachineClause) { @@ -1020,7 +927,7 @@ public class MachineContext extends DepthFirstAdapter { } public boolean machineContainsOperations() { - return operations.size() > 0; + return !operations.isEmpty(); } public AInitialisationMachineClause getInitialisationMachineClause() { diff --git a/src/main/java/de/tlc4b/analysis/PrecedenceCollector.java b/src/main/java/de/tlc4b/analysis/PrecedenceCollector.java index 1e9c694be48687f6ff9cd01a882a5688a758d541..e5e469a9e1dfd13c940c1bc849ddb558c8a7658f 100644 --- a/src/main/java/de/tlc4b/analysis/PrecedenceCollector.java +++ b/src/main/java/de/tlc4b/analysis/PrecedenceCollector.java @@ -18,7 +18,7 @@ import de.tlc4b.btypes.IntegerType; public class PrecedenceCollector extends DepthFirstAdapter { - private final static Hashtable<String, Precedence> PRECEDENCES = new Hashtable<String, Precedence>(); + private final static Hashtable<String, Precedence> PRECEDENCES = new Hashtable<>(); private static void put(String s, int from, int to, boolean leftAssociative) { PRECEDENCES.put(s, new Precedence(s, from, to, leftAssociative)); @@ -32,7 +32,7 @@ public class PrecedenceCollector extends DepthFirstAdapter { put("AEquivalencePredicate", 2, 2, false); put("ADisjunctPredicate", 3, 3, true); // or - /** and **/ + /* and **/ put("AConjunctPredicate", 3, 3, true); put("APreconditionSubstitution", 3, 3, true); put("AAssertionSubstitution", 3, 3, true); @@ -86,8 +86,8 @@ public class PrecedenceCollector extends DepthFirstAdapter { public PrecedenceCollector(Start start, Typechecker typeChecker, MachineContext machineContext, TypeRestrictor typeRestrictor) { - precedenceTable = new Hashtable<Node, Precedence>(); - brackets = new HashSet<Node>(); + precedenceTable = new Hashtable<>(); + brackets = new HashSet<>(); this.typechecker = typeChecker; start.apply(this); @@ -200,10 +200,10 @@ public class PrecedenceCollector extends DepthFirstAdapter { } class Precedence { - int from; - int to; - String name; - boolean leftAssociative; + final int from; + final int to; + final String name; + final boolean leftAssociative; public Precedence(String s, int from, int to, boolean leftAssociative) { this.from = from; @@ -226,10 +226,7 @@ class Precedence { || node.to >= parent.from && node.to <= parent.to) { return true; } - if (parent.from > node.from) - return true; - - return false; + return parent.from > node.from; } @Override diff --git a/src/main/java/de/tlc4b/analysis/PrimedNodesMarker.java b/src/main/java/de/tlc4b/analysis/PrimedNodesMarker.java index 0447ecbf93de818e2daf49bb3820c17577a2ec14..69a295555b8936b1b5bcde9441b68ec6c0f98f76 100644 --- a/src/main/java/de/tlc4b/analysis/PrimedNodesMarker.java +++ b/src/main/java/de/tlc4b/analysis/PrimedNodesMarker.java @@ -3,6 +3,7 @@ package de.tlc4b.analysis; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Set; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; import de.be4.classicalb.core.parser.node.AAssignSubstitution; @@ -17,15 +18,15 @@ import de.be4.classicalb.core.parser.util.Utils; import de.tlc4b.exceptions.ScopeException; public class PrimedNodesMarker extends DepthFirstAdapter { - private ArrayList<POperation> operations; - private MachineContext machineContext; - private HashSet<Node> primedNodes; + private final ArrayList<POperation> operations; + private final MachineContext machineContext; + private final HashSet<Node> primedNodes; private HashSet<Node> nodesToPrime; - public PrimedNodesMarker(ArrayList<POperation> operations, - MachineContext machineContext) { - this.primedNodes = new HashSet<Node>(); + public PrimedNodesMarker(ArrayList<POperation> operations, MachineContext machineContext, + Set<Node> primedNodes) { + this.primedNodes = new HashSet<>(primedNodes); this.operations = operations; this.machineContext = machineContext; } @@ -41,25 +42,22 @@ public class PrimedNodesMarker extends DepthFirstAdapter { @Override public void caseAAssignSubstitution(AAssignSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getLhsExpression()); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); for (PExpression e : copy) { Node ref = machineContext.getReferences().get(e); - if (machineContext.getVariables().values().contains(ref)) { + if (machineContext.getVariables().containsValue(ref)) { primedNodes.add(e); } - } } @Override - public void caseABecomesElementOfSubstitution( - ABecomesElementOfSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + public void caseABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { + List<PExpression> copy = new ArrayList<>( + node.getIdentifiers()); for (PExpression e : copy) { Node ref = machineContext.getReferences().get(e); - if (machineContext.getVariables().values().contains(ref)) { + if (machineContext.getVariables().containsValue(ref)) { primedNodes.add(e); } } @@ -67,9 +65,8 @@ public class PrimedNodesMarker extends DepthFirstAdapter { @Override public void caseABecomesSuchSubstitution(ABecomesSuchSubstitution node) { - nodesToPrime = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + nodesToPrime = new HashSet<>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { Node ref = machineContext.getReferences().get(e); nodesToPrime.add(ref); @@ -91,14 +88,14 @@ public class PrimedNodesMarker extends DepthFirstAdapter { @Override public void caseAPrimedIdentifierExpression(APrimedIdentifierExpression node) { - if(nodesToPrime != null){ + if (nodesToPrime != null){ Node ref = machineContext.getReferences().get(node); if (nodesToPrime.contains(ref)) { return; } } String name = Utils.getTIdentifierListAsString(node.getIdentifier()); - throw new ScopeException("Unkown identifier: '"+name+"$0'"); + throw new ScopeException("Unknown identifier: '"+name+"$0'"); } public boolean isPrimed(Node node) { diff --git a/src/main/java/de/tlc4b/analysis/Renamer.java b/src/main/java/de/tlc4b/analysis/Renamer.java index d72766838cfb4846ec85491675c3a5ecf4b47157..907739f9ce192973a7b0a26cc49769da05f31c35 100644 --- a/src/main/java/de/tlc4b/analysis/Renamer.java +++ b/src/main/java/de/tlc4b/analysis/Renamer.java @@ -35,7 +35,7 @@ public class Renamer extends DepthFirstAdapter { private final MachineContext machineContext; private final Hashtable<Node, String> namesTable; private final HashSet<String> globalNames; - private final static Set<String> KEYWORDS = new HashSet<String>(); + private final static Set<String> KEYWORDS = new HashSet<>(); static { KEYWORDS.add("ASSUME"); KEYWORDS.add("ASSUMPTION"); @@ -77,28 +77,27 @@ public class Renamer extends DepthFirstAdapter { KEYWORDS.add("Int"); KEYWORDS.add("Seq"); } - private final static Set<String> RelationsKeywords = new HashSet<String>(); + + private final static Set<String> RelationsKeywords = new HashSet<>(); static { RelationsKeywords.add("domain"); RelationsKeywords.add("range"); RelationsKeywords.add("id"); RelationsKeywords.add("set_of_relations"); RelationsKeywords.add("domain_restriction"); - RelationsKeywords.add("domain_substraction"); + RelationsKeywords.add("domain_subtraction"); RelationsKeywords.add("rel_inverse"); RelationsKeywords.add("relational_image"); RelationsKeywords.add("relational_overriding"); RelationsKeywords.add("direct"); RelationsKeywords.add("Seq"); - } public Renamer(MachineContext machineContext) { this.machineContext = machineContext; - this.namesTable = new Hashtable<Node, String>(); - this.globalNames = new HashSet<String>(); + this.namesTable = new Hashtable<>(); + this.globalNames = new HashSet<>(); start(); - } public void start() { @@ -115,9 +114,7 @@ public class Renamer extends DepthFirstAdapter { } private void evalEnumValues() { - - for (Entry<String, Node> entry : machineContext.getEnumValues() - .entrySet()) { + for (Entry<String, Node> entry : machineContext.getEnumValues().entrySet()) { String name = entry.getKey(); Node node = entry.getValue(); @@ -141,14 +138,12 @@ public class Renamer extends DepthFirstAdapter { } private void evalDefinitions() { - ADefinitionsMachineClause node = machineContext - .getDefinitionMachineClause(); + ADefinitionsMachineClause node = machineContext.getDefinitionMachineClause(); if (null == node) { return; } - List<PDefinition> copy = new ArrayList<PDefinition>( - node.getDefinitions()); + List<PDefinition> copy = new ArrayList<>(node.getDefinitions()); for (PDefinition e : copy) { String name = null; if (e instanceof AExpressionDefinitionDefinition) { @@ -190,7 +185,7 @@ public class Renamer extends DepthFirstAdapter { return res; } - private ArrayList<HashSet<String>> localContexts = new ArrayList<HashSet<String>>(); + private final ArrayList<HashSet<String>> localContexts = new ArrayList<>(); private boolean exist(String name) { if (KEYWORDS.contains(name)) @@ -199,15 +194,15 @@ public class Renamer extends DepthFirstAdapter { return true; // TODO check only if the standard module is extended - if (StandardMadules.isKeywordInModuleFunctions(name)) + if (StandardModules.isKeywordInModuleFunctions(name)) return true; - if (StandardMadules.isKeywordInModuleSequences(name)) + if (StandardModules.isKeywordInModuleSequences(name)) return true; - if (StandardMadules.isKeywordInModuleSequencesExtended(name)) + if (StandardModules.isKeywordInModuleSequencesExtended(name)) return true; - for (int i = 0; i < localContexts.size(); i++) { - if (localContexts.get(i).contains(name)) + for (HashSet<String> localContext : localContexts) { + if (localContext.contains(name)) return true; } @@ -229,20 +224,17 @@ public class Renamer extends DepthFirstAdapter { } @Override - public void inAExpressionDefinitionDefinition( - AExpressionDefinitionDefinition node) { + public void inAExpressionDefinitionDefinition(AExpressionDefinitionDefinition node) { evalDefinition(node.getParameters()); } @Override - public void inAPredicateDefinitionDefinition( - APredicateDefinitionDefinition node) { + public void inAPredicateDefinitionDefinition(APredicateDefinitionDefinition node) { evalDefinition(node.getParameters()); } @Override - public void inASubstitutionDefinitionDefinition( - ASubstitutionDefinitionDefinition node) { + public void inASubstitutionDefinitionDefinition(ASubstitutionDefinitionDefinition node) { evalDefinition(node.getParameters()); } @@ -280,8 +272,7 @@ public class Renamer extends DepthFirstAdapter { @Override public void caseAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { evalBoundedVariables(node, node.getIdentifiers()); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { e.apply(this); } @@ -291,8 +282,7 @@ public class Renamer extends DepthFirstAdapter { } @Override - public void caseAQuantifiedIntersectionExpression( - AQuantifiedIntersectionExpression node) { + public void caseAQuantifiedIntersectionExpression(AQuantifiedIntersectionExpression node) { evalBoundedVariables(node, node.getIdentifiers()); node.getPredicates().apply(this); node.getExpression().apply(this); @@ -317,7 +307,7 @@ public class Renamer extends DepthFirstAdapter { @Override public void caseAOperation(AOperation node) { - List<PExpression> list = new ArrayList<PExpression>(); + List<PExpression> list = new ArrayList<>(); list.addAll(node.getParameters()); list.addAll(node.getReturnValues()); evalBoundedVariables(node, list); @@ -326,7 +316,7 @@ public class Renamer extends DepthFirstAdapter { } private void evalBoundedVariables(Node node, List<PExpression> params) { - HashSet<String> context = new HashSet<String>(); + HashSet<String> context = new HashSet<>(); for (PExpression e : params) { String newName = renameIdentifier(e); context.add(newName); @@ -336,12 +326,10 @@ public class Renamer extends DepthFirstAdapter { @Override public void caseAAnySubstitution(AAnySubstitution node) { - List<PExpression> list = new ArrayList<PExpression>(); - list.addAll(node.getIdentifiers()); + List<PExpression> list = new ArrayList<>(node.getIdentifiers()); evalBoundedVariables(node, list); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { e.apply(this); } @@ -352,12 +340,10 @@ public class Renamer extends DepthFirstAdapter { @Override public void caseALetSubstitution(ALetSubstitution node) { - List<PExpression> list = new ArrayList<PExpression>(); - list.addAll(node.getIdentifiers()); + List<PExpression> list = new ArrayList<>(node.getIdentifiers()); evalBoundedVariables(node, list); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { e.apply(this); } @@ -368,11 +354,9 @@ public class Renamer extends DepthFirstAdapter { @Override public void caseAVarSubstitution(AVarSubstitution node) { - List<PExpression> list = new ArrayList<PExpression>(); - list.addAll(node.getIdentifiers()); + List<PExpression> list = new ArrayList<>(node.getIdentifiers()); evalBoundedVariables(node, list); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { e.apply(this); } diff --git a/src/main/java/de/tlc4b/analysis/StandardMadules.java b/src/main/java/de/tlc4b/analysis/StandardModules.java similarity index 88% rename from src/main/java/de/tlc4b/analysis/StandardMadules.java rename to src/main/java/de/tlc4b/analysis/StandardModules.java index e85c5475483801131cbb56242a42572cd9d00baf..0de0799d5bc4aa96068fe5cd5959785f63faef3d 100644 --- a/src/main/java/de/tlc4b/analysis/StandardMadules.java +++ b/src/main/java/de/tlc4b/analysis/StandardModules.java @@ -5,9 +5,9 @@ import java.util.HashSet; import java.util.Set; -public final class StandardMadules { +public final class StandardModules { - private StandardMadules() { + private StandardModules() { } // Functions @@ -16,26 +16,26 @@ public final class StandardMadules { public static final String FUNC_ID = "Id"; public static final String FUNC_INVERSE = "Inverse"; public static final String FUNC_DOMAIN_RESTRICTION = "DomRes"; - public static final String FUNC_DOMAIN_SUBSTRACTION = "DomSub"; + public static final String FUNC_DOMAIN_SUBTRACTION = "DomSub"; public static final String FUNC_RANGE_RESTRICTION = "RanRes"; - public static final String FUNC_RANGE_SUBSTRACTION = "RanSub"; + public static final String FUNC_RANGE_SUBTRACTION = "RanSub"; public static final String FUNC_OVERRIDE = "Override"; public static final String FUNC_ASSIGN = "FuncAssign"; - private static final ArrayList<String> functions = new ArrayList<String>(); + private static final ArrayList<String> functions = new ArrayList<>(); static { functions.add(FUNC_RANGE); functions.add(FUNC_ID); functions.add(FUNC_INVERSE); functions.add(FUNC_DOMAIN_RESTRICTION); - functions.add(FUNC_DOMAIN_SUBSTRACTION); + functions.add(FUNC_DOMAIN_SUBTRACTION); functions.add(FUNC_RANGE_RESTRICTION); - functions.add(FUNC_RANGE_SUBSTRACTION); + functions.add(FUNC_RANGE_SUBTRACTION); functions.add(FUNC_OVERRIDE); functions.add(FUNC_ASSIGN); } - public static final boolean isKeywordInModuleFunctions(String name) { + public static boolean isKeywordInModuleFunctions(String name) { return functions.contains(name); } @@ -55,8 +55,8 @@ public final class StandardMadules { public static final String PARTIAL_SURJECTIVE_FUNCTION = "ParSurFunc"; public static final String PARTIAL_SURJECTIVE_FUNCTION_ELEMENT_OF = "ParSurFuncEleOf"; // bijective - public static final String PARITAL_BIJECTIVE_FUNCTION = "ParBijFunc"; - public static final String PARITAL_BIJECTIVE_FUNCTION_ELEMENT_OF = "ParBijFuncEleOf"; + public static final String PARTIAL_BIJECTIVE_FUNCTION = "ParBijFunc"; + public static final String PARTIAL_BIJECTIVE_FUNCTION_ELEMENT_OF = "ParBijFuncEleOf"; // Relations public static final String RELATIONS = "Relations"; @@ -64,9 +64,9 @@ public final class StandardMadules { public static final String REL_RANGE = "RelRange"; public static final String REL_ID = "RelId"; public static final String REL_DOMAIN_RESTRICTION = "RelDomRes"; - public static final String REL_DOMAIN_SUBSTRACTION = "RelDomSub"; + public static final String REL_DOMAIN_SUBTRACTION = "RelDomSub"; public static final String REL_RANGE_RESTRICTION = "RelRanRes"; - public static final String REL_RANGE_SUBSTRACTION = "RelRanSub"; + public static final String REL_RANGE_SUBTRACTION = "RelRanSub"; public static final String REL_INVERSE = "RelInverse"; public static final String REL_IMAGE = "RelImage"; public static final String REL_OVERRIDING = "RelOverride"; @@ -110,7 +110,7 @@ public final class StandardMadules { public static final String REL_PARTIAL_BIJECTIVE_FUNCTION = "RelParBijFunc"; public static final String REL_PARTIAL_BIJECTIVE_FUNCTION_ELEMENT_OF = "RelParBijFuncEleOf"; - private final static Set<String> SequencesKeywords = new HashSet<String>(); + private final static Set<String> SequencesKeywords = new HashSet<>(); static { SequencesKeywords.add("Seq"); SequencesKeywords.add("Len"); @@ -121,7 +121,7 @@ public final class StandardMadules { SequencesKeywords.add("SelectSeq"); } - public final static boolean isKeywordInModuleSequences(String name) { + public static boolean isKeywordInModuleSequences(String name) { return SequencesKeywords.contains(name); } @@ -136,11 +136,11 @@ public final class StandardMadules { public static final String INJECTIVE_SEQUENCE_1_ELEMENT_OF = "ISeq1EleOf"; public static final String SEQUENCE_PERMUTATION = "Perm"; public static final String SEQUENCE_REVERSE = "Reverse"; - public static final String SEQUENCE_GENERAL_CONCATINATION = "Conc"; + public static final String SEQUENCE_GENERAL_CONCATENATION = "Conc"; public static final String SEQUENCE_TAKE_FIRST_ELEMENTS = "TakeFirstElements"; public static final String SEQUENCE_DROP_FIRST_ELEMENTS = "DropFirstElements"; - private final static Set<String> SequencesExtendedKeywords = new HashSet<String>(); + private final static Set<String> SequencesExtendedKeywords = new HashSet<>(); static { SequencesExtendedKeywords.add(SEQUENCE_LAST_ELEMENT); SequencesExtendedKeywords.add(SEQUENCE_PREPEND_ELEMENT); @@ -152,12 +152,12 @@ public final class StandardMadules { SequencesExtendedKeywords.add(INJECTIVE_SEQUENCE_1_ELEMENT_OF); SequencesExtendedKeywords.add(SEQUENCE_PERMUTATION); SequencesExtendedKeywords.add(SEQUENCE_REVERSE); - SequencesExtendedKeywords.add(SEQUENCE_GENERAL_CONCATINATION); + SequencesExtendedKeywords.add(SEQUENCE_GENERAL_CONCATENATION); SequencesExtendedKeywords.add(SEQUENCE_TAKE_FIRST_ELEMENTS); SequencesExtendedKeywords.add(SEQUENCE_DROP_FIRST_ELEMENTS); } - public final static boolean isKeywordInModuleSequencesExtended(String name) { + public static boolean isKeywordInModuleSequencesExtended(String name) { return SequencesExtendedKeywords.contains(name); } @@ -174,7 +174,7 @@ public final class StandardMadules { public static final String REL_INJECTIVE_SEQUENCE_1 = "RelISeq1"; public static final String REL_INJECTIVE_SEQUENCE_1_ELEMENT_OF = "RelISeq1EleOf"; public static final String REL_SEQUENCE_Concat = "RelSeqConcat"; - public static final String REL_SEQUENCE_PREPAND = "RelSeqPrepand"; + public static final String REL_SEQUENCE_PREPEND = "RelSeqPrepend"; public static final String REL_SEQUENCE_APPEND = "RelSeqAppend"; public static final String REL_SEQUENCE_REVERSE = "RelSeqReverse"; public static final String REL_SEQUENCE_FIRST_ELEMENT = "RelSeqFirst"; @@ -182,7 +182,7 @@ public final class StandardMadules { public static final String REL_SEQUENCE_FRONT = "RelSeqFront"; public static final String REL_SEQUENCE_TAIL = "RelSeqTail"; public static final String REL_SEQUENCE_PERM = "RelSeqPerm"; - public static final String REL_SEQUENCE_GENERAL_CONCATINATION = "RelSeqConc"; + public static final String REL_SEQUENCE_GENERAL_CONCATENATION = "RelSeqConc"; public static final String REL_SEQUENCE_TAKE_FIRST_ELEMENTS = "RelSeqTakeFirstElements"; public static final String REL_SEQUENCE_DROP_FIRST_ELEMENTS = "RelSeqDropFirstElements"; @@ -204,16 +204,16 @@ public final class StandardMadules { public static final String GENERAL_SUMMATION = "Sigma"; public static final String GENERAL_PRODUCT = "Pi"; - private static final ArrayList<String> Relations = new ArrayList<String>(); + private static final ArrayList<String> Relations = new ArrayList<>(); static { Relations.add(RELATIONS); Relations.add(REL_DOMAIN); Relations.add(REL_RANGE); Relations.add(REL_ID); Relations.add(REL_DOMAIN_RESTRICTION); - Relations.add(REL_DOMAIN_SUBSTRACTION); + Relations.add(REL_DOMAIN_SUBTRACTION); Relations.add(REL_RANGE_RESTRICTION); - Relations.add(REL_RANGE_SUBSTRACTION); + Relations.add(REL_RANGE_SUBTRACTION); Relations.add(REL_INVERSE); Relations.add(REL_IMAGE); Relations.add(REL_OVERRIDING); @@ -229,7 +229,7 @@ public final class StandardMadules { } - public static final boolean containsNameFromModuleRelations(String name) { + public static boolean containsNameFromModuleRelations(String name) { return Relations.contains(name); } @@ -253,7 +253,7 @@ public final class StandardMadules { public static final String STRING_TO_INT = "STRING_TO_INT"; public static final String DECIMAL_TO_INT = "DECIMAL_TO_INT"; - private static final ArrayList<String> ExternalFunctions = new ArrayList<String>(); + private static final ArrayList<String> ExternalFunctions = new ArrayList<>(); static { ExternalFunctions.add(EXTERNAL_printf); ExternalFunctions.add(INT_TO_STRING); @@ -266,11 +266,7 @@ public final class StandardMadules { } public static boolean isAbstractConstant(String name) { - if (name.equals(SORT_SET) || name.equals(DECIMAL_TO_INT)) { - return true; - } else { - return false; - } + return name.equals(SORT_SET) || name.equals(DECIMAL_TO_INT); } diff --git a/src/main/java/de/tlc4b/analysis/Typechecker.java b/src/main/java/de/tlc4b/analysis/Typechecker.java index afb181e38ad6a9c0b574e15bd12fac1a25816f0e..b76c6da8037890f5c2239271e034afd76e7247a1 100644 --- a/src/main/java/de/tlc4b/analysis/Typechecker.java +++ b/src/main/java/de/tlc4b/analysis/Typechecker.java @@ -30,6 +30,8 @@ import de.tlc4b.exceptions.UnificationException; import de.tlc4b.ltl.LTLBPredicate; import de.tlc4b.ltl.LTLFormulaVisitor; +import static de.tlc4b.util.UtilMethods.getIdentifierExpression; + /** * TODO we need a second run over the AST to check if all local variables have a * type. This run should be performed after the normal model checking task. @@ -41,7 +43,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { private final MachineContext machineContext; public Typechecker(MachineContext context) { - this.types = new Hashtable<Node, BType>(); + this.types = new Hashtable<>(); this.referenceTable = context.getReferences(); this.machineContext = context; @@ -52,8 +54,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { private void checkLTLFormulas() { ArrayList<LTLFormulaVisitor> visitors = machineContext.getLTLFormulas(); - for (int i = 0; i < visitors.size(); i++) { - LTLFormulaVisitor visitor = visitors.get(i); + for (LTLFormulaVisitor visitor : visitors) { Collection<AIdentifierExpression> parameter = visitor.getParameter(); for (AIdentifierExpression param : parameter) { setType(param, new UntypedType()); @@ -105,6 +106,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { public BType getType(Node node) { BType res = types.get(node); if (res == null) { + // there are failing tests if this is thrown due to new ASetExtensionExpressions after type checking new TypeErrorException("Node '" + node + "' has no type.\n" + node.getStartPos()); } return res; @@ -119,7 +121,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { node.getHeader().apply(this); } { - List<PMachineClause> copy = new ArrayList<PMachineClause>(node.getMachineClauses()); + List<PMachineClause> copy = new ArrayList<>(node.getMachineClauses()); for (PMachineClause e : copy) { e.apply(this); } @@ -132,7 +134,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAMachineHeader(AMachineHeader node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { AIdentifierExpression p = (AIdentifierExpression) e; String name = Utils.getTIdentifierListAsString(p.getIdentifier()); @@ -150,7 +152,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseASetsMachineClause(ASetsMachineClause node) { - List<PSet> copy = new ArrayList<PSet>(node.getSetDefinitions()); + List<PSet> copy = new ArrayList<>(node.getSetDefinitions()); for (PSet e : copy) { e.apply(this); } @@ -158,12 +160,12 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAEnumeratedSetSet(AEnumeratedSetSet node) { - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>(node.getIdentifier()); + List<TIdentifierLiteral> copy = new ArrayList<>(node.getIdentifier()); String setName = Utils.getTIdentifierListAsString(copy); SetType set = new SetType(new EnumeratedSetElement(setName)); setType(node, set); - List<PExpression> copy2 = new ArrayList<PExpression>(node.getElements()); + List<PExpression> copy2 = new ArrayList<>(node.getElements()); for (PExpression e : copy2) { setType(e, set.getSubtype()); } @@ -171,49 +173,33 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseADeferredSetSet(ADeferredSetSet node) { - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>(node.getIdentifier()); + List<TIdentifierLiteral> copy = new ArrayList<>(node.getIdentifier()); String name = Utils.getTIdentifierListAsString(copy); setType(node, new SetType(new EnumeratedSetElement(name))); } @Override public void caseAConstantsMachineClause(AConstantsMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression id = (AIdentifierExpression) e; - UntypedType u = new UntypedType(); - setType(id, u); - } + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + copy.forEach(e -> setType(getIdentifierExpression(e), new UntypedType())); } @Override public void caseAAbstractConstantsMachineClause(AAbstractConstantsMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression id = (AIdentifierExpression) e; - UntypedType u = new UntypedType(); - setType(id, u); - } + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + copy.forEach(e -> setType(getIdentifierExpression(e), new UntypedType())); } @Override public void caseAVariablesMachineClause(AVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression v = (AIdentifierExpression) e; - UntypedType u = new UntypedType(); - setType(v, u); - } + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + copy.forEach(e -> setType(getIdentifierExpression(e), new UntypedType())); } @Override public void caseAConcreteVariablesMachineClause(AConcreteVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - for (PExpression e : copy) { - AIdentifierExpression v = (AIdentifierExpression) e; - UntypedType u = new UntypedType(); - setType(v, u); - } + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + copy.forEach(e -> setType(getIdentifierExpression(e), new UntypedType())); } /** @@ -222,7 +208,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseADefinitionsMachineClause(ADefinitionsMachineClause node) { - List<PDefinition> copy = new ArrayList<PDefinition>(node.getDefinitions()); + List<PDefinition> copy = new ArrayList<>(node.getDefinitions()); for (PDefinition e : copy) { setType(e, new UntypedType()); } @@ -235,7 +221,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override // d(a) == 1 public void caseAExpressionDefinitionDefinition(AExpressionDefinitionDefinition node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { UntypedType u = new UntypedType(); setType(e, u); @@ -248,7 +234,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { // d(a) == 1 = 1 public void caseAPredicateDefinitionDefinition(APredicateDefinitionDefinition node) { setType(node, BoolType.getInstance()); - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { setType(e, new UntypedType()); } @@ -266,10 +252,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + expected + "', found '" + found + "' at definition call\n"); + throw new TypeErrorException("Expected '" + expected + "', found '" + found + "' at definition call\n", e); } LinkedList<PExpression> params = ((AExpressionDefinitionDefinition) originalDef).getParameters(); - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (int i = 0; i < params.size(); i++) { BType type = getType(params.get(i)); setType(copy.get(i), type); @@ -286,10 +272,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + expected + "', found '" + found + "' at definition call\n"); + throw new TypeErrorException("Expected '" + expected + "', found '" + found + "' at definition call\n", e); } LinkedList<PExpression> params = ((APredicateDefinitionDefinition) originalDef).getParameters(); - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (int i = 0; i < params.size(); i++) { setType(copy.get(i), getType(params.get(i))); copy.get(i).apply(this); @@ -345,7 +331,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAAssertionsMachineClause(AAssertionsMachineClause node) { - List<PPredicate> copy = new ArrayList<PPredicate>(node.getPredicates()); + List<PPredicate> copy = new ArrayList<>(node.getPredicates()); for (PPredicate e : copy) { setType(e, BoolType.getInstance()); e.apply(this); @@ -362,16 +348,15 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAOperation(AOperation node) { { - List<PExpression> copy = new ArrayList<PExpression>(node.getReturnValues()); + List<PExpression> copy = new ArrayList<>(node.getReturnValues()); for (PExpression e : copy) { AIdentifierExpression id = (AIdentifierExpression) e; UntypedType u = new UntypedType(); setType(id, u); } - } { - List<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { AIdentifierExpression id = (AIdentifierExpression) e; UntypedType u = new UntypedType(); @@ -403,8 +388,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "' at identifier " + name - + "\n" + node.getStartPos()); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "' at identifier " + name + "\n" + node.getStartPos(), e); } } @@ -413,7 +397,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at '=' \n" + node.getStartPos()); + throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at '=' \n" + node.getStartPos(), e); } UntypedType x = new UntypedType(); @@ -442,7 +426,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at '=' \n" + node.getClass()); + throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at '=' \n" + node.getClass(), e); } UntypedType x = new UntypedType(); @@ -457,10 +441,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at 'For All' \n"); + throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at 'For All' \n", e); } - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -475,10 +459,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at 'Exists' \n"); + throw new TypeErrorException("Expected '" + getType(node) + "', found BOOL at 'Exists' \n", e); } - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -512,7 +496,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { setType(node.getCondition(), BoolType.getInstance()); node.getCondition().apply(this); node.getThen().apply(this); - List<PSubstitution> copy = new ArrayList<PSubstitution>(node.getWhenSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getWhenSubstitutions()); for (PSubstitution e : copy) { e.apply(this); } @@ -533,7 +517,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { setType(node.getCondition(), BoolType.getInstance()); node.getCondition().apply(this); node.getThen().apply(this); - List<PSubstitution> copy = new ArrayList<PSubstitution>(node.getElsifSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getElsifSubstitutions()); for (PSubstitution e : copy) { e.apply(this); } @@ -551,8 +535,8 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAAssignSubstitution(AAssignSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getLhsExpression()); - List<PExpression> copy2 = new ArrayList<PExpression>(node.getRhsExpressions()); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); + List<PExpression> copy2 = new ArrayList<>(node.getRhsExpressions()); for (int i = 0; i < copy.size(); i++) { PExpression left = copy.get(i); @@ -565,7 +549,6 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { left.apply(this); right.apply(this); } - } @Override @@ -576,7 +559,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); SetType set = new SetType(new UntypedType()); setType(node.getSet(), set); @@ -591,7 +574,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAAnySubstitution(AAnySubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -603,7 +586,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseALetSubstitution(ALetSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -622,8 +605,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException( - "Excepted '" + getType(node) + "' , found 'INTEGER' in '" + node.getLiteral().getText() + "'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in '" + node.getLiteral().getText() + "'", e); } } @@ -633,7 +615,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'INTEGER'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'INTEGER'", e); } } @@ -643,7 +625,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NATURAL'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NATURAL'", e); } } @@ -653,7 +635,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NATURAL1'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NATURAL1'", e); } } @@ -663,7 +645,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'INT'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'INT'", e); } } @@ -673,7 +655,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NAT'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NAT'", e); } } @@ -683,7 +665,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NAT1'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' in 'NAT1'", e); } } @@ -692,7 +674,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in '-'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in '-'", e); } } @@ -702,8 +684,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(IntegerType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException( - "Excepted '" + getType(node) + "' , found 'POW(INTEGER)' at interval operator"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(INTEGER)' at interval operator", e); } setType(node.getLeftBorder(), IntegerType.getInstance()); @@ -727,7 +708,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' > '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' > '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -740,7 +721,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' < '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' < '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -753,7 +734,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' >= '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' >= '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -766,7 +747,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' <= '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' <= '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -779,7 +760,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' min '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' min '", e); } setType(node.getExpression(), new SetType(IntegerType.getInstance())); node.getExpression().apply(this); @@ -790,7 +771,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' min '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' min '", e); } setType(node.getExpression(), new SetType(IntegerType.getInstance())); node.getExpression().apply(this); @@ -801,7 +782,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' + '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' + '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -829,12 +810,11 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { IntegerOrSetOfPairType found = new IntegerOrSetOfPairType(node.getStartPos(), node.getEndPos()); // setType(node.getLeft(), found.getFirst()); // setType(node.getRight(), found.getSecond()); - BType result = null; + BType result; try { result = expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "' at " - + node.getClass().getSimpleName() + "\n " + node.getStartPos()); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "' at " + node.getClass().getSimpleName() + "\n " + node.getStartPos(), e); } // // BType res2 = getType(node); @@ -868,7 +848,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' / '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' / '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -881,7 +861,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' ** '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' ** '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -894,7 +874,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' mod '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'INTEGER' in ' mod '", e); } setType(node.getLeft(), IntegerType.getInstance()); setType(node.getRight(), IntegerType.getInstance()); @@ -920,10 +900,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + "INTEGER" + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + "INTEGER" + "'", e); } - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -942,10 +922,10 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { IntegerType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + "INTEGER" + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + "INTEGER" + "'", e); } - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -967,7 +947,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'TRUE'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'TRUE'", e); } } @@ -976,7 +956,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'FALSE'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'FALSE'", e); } } @@ -986,7 +966,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { SetType found = new SetType(BoolType.getInstance()); found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(BOOL)' in 'BOOL'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'POW(BOOL)' in 'BOOL'", e); } } @@ -995,7 +975,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'bool(...)'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in 'bool(...)'", e); } setType(node.getPredicate(), BoolType.getInstance()); node.getPredicate().apply(this); @@ -1010,8 +990,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException( - "Excepted '" + getType(node) + "' , found 'BOOL' in ' & '." + node.getStartPos()); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' & '." + node.getStartPos(), e); } setType(node.getLeft(), BoolType.getInstance()); setType(node.getRight(), BoolType.getInstance()); @@ -1024,7 +1003,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' or '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' or '", e); } setType(node.getLeft(), BoolType.getInstance()); setType(node.getRight(), BoolType.getInstance()); @@ -1037,7 +1016,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' => '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' => '", e); } setType(node.getLeft(), BoolType.getInstance()); setType(node.getRight(), BoolType.getInstance()); @@ -1051,7 +1030,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { System.out.println(node.parent().getClass()); - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' <=> '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' <=> '", e); } setType(node.getLeft(), BoolType.getInstance()); setType(node.getRight(), BoolType.getInstance()); @@ -1064,7 +1043,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' not '"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found 'BOOL' in ' not '", e); } setType(node.getPredicate(), BoolType.getInstance()); node.getPredicate().apply(this); @@ -1077,9 +1056,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAEmptySetExpression(AEmptySetExpression node) { BType expected = getType(node); - if (expected instanceof FunctionType) { - return; - } else { + if (!(expected instanceof FunctionType)) { unify(expected, new SetType(new UntypedType()), node); } } @@ -1093,7 +1070,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { setType(e, u); } BType expected = getType(node); - List<PExpression> copy = new ArrayList<PExpression>(node.getExpressions()); + List<PExpression> copy = new ArrayList<>(node.getExpressions()); for (PExpression e : copy) { e.apply(this); } @@ -1102,8 +1079,8 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { } private boolean functionTest(ASetExtensionExpression node) { - ArrayList<Node> list1 = new ArrayList<Node>(); - ArrayList<Node> list2 = new ArrayList<Node>(); + ArrayList<Node> list1 = new ArrayList<>(); + ArrayList<Node> list2 = new ArrayList<>(); try { for (PExpression e : node.getExpressions()) { ACoupleExpression couple = (ACoupleExpression) e; @@ -1145,9 +1122,9 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { } try { if (list.get(0) instanceof AIntegerExpression) { - HashSet<Integer> set = new HashSet<Integer>(); - for (int i = 0; i < list.size(); i++) { - AIntegerExpression aInt = (AIntegerExpression) list.get(i); + HashSet<Integer> set = new HashSet<>(); + for (Node node : list) { + AIntegerExpression aInt = (AIntegerExpression) node; int integer = Integer.parseInt(aInt.getLiteral().getText()); set.add(integer); } @@ -1155,9 +1132,9 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { return true; } } else if (list.get(0) instanceof AIdentifierExpression) { - HashSet<Node> set = new HashSet<Node>(); - for (int i = 0; i < list.size(); i++) { - AIdentifierExpression id = (AIdentifierExpression) list.get(i); + HashSet<Node> set = new HashSet<>(); + for (Node node : list) { + AIdentifierExpression id = (AIdentifierExpression) node; Node enumValue = machineContext.getReferences().get(id); if (!machineContext.getEnumValues().containsValue(enumValue)) { return false; @@ -1169,15 +1146,15 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { } } - } catch (ClassCastException e) { + } catch (ClassCastException ignored) { } return false; } @Override public void caseAComprehensionSetExpression(AComprehensionSetExpression node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); - ArrayList<BType> typesList = new ArrayList<BType>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + ArrayList<BType> typesList = new ArrayList<>(); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; UntypedType u = new UntypedType(); @@ -1190,7 +1167,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + found + "'", e); } setType(node.getPredicates(), BoolType.getInstance()); @@ -1200,7 +1177,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseAEventBComprehensionSetExpression(AEventBComprehensionSetExpression node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -1238,7 +1215,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found = found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found 'POW(POW(_A))' in 'POW'"); + throw new TypeErrorException("Excepted '" + expected + "' , found 'POW(POW(_A))' in 'POW'", e); } setType(expr, found.getSubtype()); @@ -1265,14 +1242,14 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { subset(node, node.getExpression()); } - // union, intersection, substraction, + // union, intersection, subtraction, private void setSetSet(Node node, Node left, Node right) { SetType found = new SetType(new UntypedType()); BType expected = getType(node); try { found = found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } setType(left, found); setType(right, found); @@ -1303,7 +1280,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } setType(node.getExpression(), new UntypedType()); @@ -1342,7 +1319,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'"); + throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'", e); } SetType set = new SetType(new UntypedType()); @@ -1359,7 +1336,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'"); + throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'", e); } SetType set = new SetType(new UntypedType()); @@ -1377,7 +1354,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'"); + throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'", e); } SetType set = new SetType(new UntypedType()); @@ -1395,7 +1372,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { BoolType.getInstance().unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'"); + throw new TypeErrorException("Excepted '" + expected + "' , found 'BOOL'", e); } SetType set = new SetType(new UntypedType()); @@ -1418,7 +1395,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "'", e); } } @@ -1433,14 +1410,14 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + found + "'", e); } } @Override public void caseAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { BType expected = getType(node); - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; UntypedType u = new UntypedType(); @@ -1456,14 +1433,14 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @Override public void caseAQuantifiedIntersectionExpression(AQuantifiedIntersectionExpression node) { BType expected = getType(node); - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; UntypedType u = new UntypedType(); @@ -1479,7 +1456,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -1489,7 +1466,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { @Override public void caseALambdaExpression(ALambdaExpression node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { AIdentifierExpression v = (AIdentifierExpression) e; setType(v, new UntypedType()); @@ -1501,7 +1478,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { setType(node.getExpression(), new UntypedType()); node.getExpression().apply(this); - ArrayList<BType> typesList = new ArrayList<BType>(); + ArrayList<BType> typesList = new ArrayList<>(); for (PExpression e : copy) { typesList.add(getType(e)); } @@ -1515,7 +1492,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -1540,16 +1517,16 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { rangeFound.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + rangeFound + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + rangeFound + "'", e); } - ArrayList<PExpression> copy = new ArrayList<PExpression>(node.getParameters()); + ArrayList<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { setType(e, new UntypedType()); e.apply(this); } - ArrayList<BType> foundList = new ArrayList<BType>(); + ArrayList<BType> foundList = new ArrayList<>(); for (PExpression e : copy) { foundList.add(getType(e)); } @@ -1558,7 +1535,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { domainFound.unify(p, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + domainFound + "' , found '" + makePair(foundList) + "'"); + throw new TypeErrorException("Excepted '" + domainFound + "' , found '" + makePair(foundList) + "'", e); } } @@ -1580,7 +1557,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { domainFound.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + domainFound + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + domainFound + "'", e); } } @@ -1602,7 +1579,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { rangeFound.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found '" + rangeFound + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found '" + rangeFound + "'", e); } } @@ -1704,7 +1681,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -1716,9 +1693,9 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { public void caseACoupleExpression(ACoupleExpression node) { BType expected = getType(node); - List<PExpression> copy = new ArrayList<PExpression>(node.getList()); + List<PExpression> copy = new ArrayList<>(node.getList()); - ArrayList<BType> list = new ArrayList<BType>(); + ArrayList<BType> list = new ArrayList<>(); for (PExpression e : copy) { setType(e, new UntypedType()); @@ -1733,7 +1710,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -1752,7 +1729,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -1889,7 +1866,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } node.getLeft().apply(this); @@ -2027,8 +2004,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "' at " - + node.getClass().getSimpleName() + "\n " + node.getStartPos() + ":" + node.getEndPos()); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "' at " + node.getClass().getSimpleName() + "\n " + node.getStartPos() + ":" + node.getEndPos(), e); } } @@ -2039,7 +2015,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { expected.unify(found, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -2226,7 +2202,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found = found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } BType subtype; if (found instanceof FunctionType) { @@ -2238,7 +2214,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { for (PExpression e : node.getExpression()) { setType(e, subtype); } - List<PExpression> copy = new ArrayList<PExpression>(node.getExpression()); + List<PExpression> copy = new ArrayList<>(node.getExpression()); for (PExpression e : copy) { e.apply(this); } @@ -2253,29 +2229,27 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { StructType found = new StructType(); found.setComplete(); - List<PRecEntry> copy = new ArrayList<PRecEntry>(node.getEntries()); + List<PRecEntry> copy = new ArrayList<>(node.getEntries()); for (PRecEntry e2 : copy) { ARecEntry e = (ARecEntry) e2; setType(e.getValue(), new UntypedType()); e.getValue().apply(this); - AIdentifierExpression i = (AIdentifierExpression) e.getIdentifier(); - String name = Utils.getTIdentifierListAsString(i.getIdentifier()); + String name = e.getIdentifier().getText(); found.add(name, getType(e.getValue())); } BType expected = getType(node); try { unify(expected, found, node); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @Override public void caseARecordFieldExpression(ARecordFieldExpression node) { StructType s = new StructType(); - AIdentifierExpression i = (AIdentifierExpression) node.getIdentifier(); - String fieldName = Utils.getTIdentifierListAsString(i.getIdentifier()); + String fieldName = node.getIdentifier().getText(); s.add(fieldName, new UntypedType()); setType(node.getRecord(), s); @@ -2286,9 +2260,8 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { unify(expected, found, node); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } - } @Override @@ -2296,14 +2269,13 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { StructType s = new StructType(); s.setComplete(); - List<PRecEntry> copy = new ArrayList<PRecEntry>(node.getEntries()); + List<PRecEntry> copy = new ArrayList<>(node.getEntries()); for (PRecEntry e2 : copy) { ARecEntry e = (ARecEntry) e2; setType(e.getValue(), new SetType(new UntypedType())); e.getValue().apply(this); - AIdentifierExpression i = (AIdentifierExpression) e.getIdentifier(); - String name = Utils.getTIdentifierListAsString(i.getIdentifier()); + String name = e.getIdentifier().getText(); BType t = ((SetType) getType(e.getValue())).getSubtype(); s.add(name, t); } @@ -2313,7 +2285,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(expected, this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + expected + "' , found " + found + "'", e); } } @@ -2326,7 +2298,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { StringType.getInstance().unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + StringType.getInstance() + "'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + StringType.getInstance() + "'", e); } } @@ -2336,7 +2308,7 @@ public class Typechecker extends DepthFirstAdapter implements ITypechecker { try { found.unify(getType(node), this); } catch (UnificationException e) { - throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + found + "'"); + throw new TypeErrorException("Excepted '" + getType(node) + "' , found " + found + "'", e); } } diff --git a/src/main/java/de/tlc4b/analysis/UnsupportedConstructsFinder.java b/src/main/java/de/tlc4b/analysis/UnsupportedConstructsFinder.java index ca12eb32e9764b885a769745f118806c2a733e96..21ddc60bca560bdd8223a0e7f5e239fe0586d3ee 100644 --- a/src/main/java/de/tlc4b/analysis/UnsupportedConstructsFinder.java +++ b/src/main/java/de/tlc4b/analysis/UnsupportedConstructsFinder.java @@ -8,22 +8,11 @@ import java.util.List; import java.util.Set; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; -import de.be4.classicalb.core.parser.node.ACaseSubstitution; -import de.be4.classicalb.core.parser.node.AExtendsMachineClause; -import de.be4.classicalb.core.parser.node.AImplementationMachineParseUnit; -import de.be4.classicalb.core.parser.node.AImportsMachineClause; -import de.be4.classicalb.core.parser.node.AIncludesMachineClause; -import de.be4.classicalb.core.parser.node.APromotesMachineClause; -import de.be4.classicalb.core.parser.node.ARefinesModelClause; -import de.be4.classicalb.core.parser.node.ASequenceSubstitution; -import de.be4.classicalb.core.parser.node.AVarSubstitution; -import de.be4.classicalb.core.parser.node.AWhileSubstitution; -import de.be4.classicalb.core.parser.node.Node; -import de.be4.classicalb.core.parser.node.Start; +import de.be4.classicalb.core.parser.node.*; import de.tlc4b.exceptions.NotSupportedException; public class UnsupportedConstructsFinder extends DepthFirstAdapter { - private final Start start; + private static final Set<Class<? extends Node>> unsupportedClasses = new HashSet<>(); static { @@ -34,33 +23,27 @@ public class UnsupportedConstructsFinder extends DepthFirstAdapter { add(AImportsMachineClause.class); add(AWhileSubstitution.class); - add(ASequenceSubstitution.class); add(AVarSubstitution.class); add(ACaseSubstitution.class); add(AImplementationMachineParseUnit.class); + + add(ARealSetExpression.class); + add(AFloatSetExpression.class); + add(ARealExpression.class); } private static void add(Class<? extends Node> clazz) { unsupportedClasses.add(clazz); } - public UnsupportedConstructsFinder(Start start) { - this.start = start; - } - - public void find() { - start.apply(this); - } - - private static final List<String> SUM_TYPE = new LinkedList<String>( - Arrays.asList("model_clause", "machine_clause", "substitution", "machine_parse_unit")); + private static final List<String> SUM_TYPE = new LinkedList<>( + Arrays.asList("model_clause", "machine_clause", "substitution", "machine_parse_unit")); private String formatCamel(final String input) { StringWriter out = new StringWriter(); char[] chars = input.toCharArray(); - for (int i = 0; i < chars.length; i++) { - char current = chars[i]; + for (char current : chars) { if (Character.isUpperCase(current)) { out.append('_'); out.append(Character.toLowerCase(current)); diff --git a/src/main/java/de/tlc4b/analysis/UsedStandardModules.java b/src/main/java/de/tlc4b/analysis/UsedStandardModules.java index a5ff66c597b4501b9a9eefb9f6e26d08c878b769..f39d45299e0a109351f1df0e33e0141330203eb0 100644 --- a/src/main/java/de/tlc4b/analysis/UsedStandardModules.java +++ b/src/main/java/de/tlc4b/analysis/UsedStandardModules.java @@ -1,11 +1,10 @@ package de.tlc4b.analysis; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.Collections; +import java.util.stream.Collectors; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; import de.be4.classicalb.core.parser.node.AAddExpression; @@ -105,37 +104,36 @@ import de.tlc4b.btypes.SetType; import de.tlc4b.tla.TLAModule; public class UsedStandardModules extends DepthFirstAdapter { - - public static enum STANDARD_MODULES { + private enum StandardModule { Naturals, Integers, FiniteSets, Sequences, TLC, BBuiltIns, Relations, FunctionsAsRelations, Functions, SequencesExtended, SequencesAsRelations, ExternalFunctions, Foo } - private final static ArrayList<STANDARD_MODULES> modules = new ArrayList<UsedStandardModules.STANDARD_MODULES>(); + private final static ArrayList<StandardModule> modules = new ArrayList<>(); static { - modules.add(STANDARD_MODULES.Naturals); - modules.add(STANDARD_MODULES.Integers); - modules.add(STANDARD_MODULES.FiniteSets); - modules.add(STANDARD_MODULES.Sequences); - modules.add(STANDARD_MODULES.TLC); - modules.add(STANDARD_MODULES.BBuiltIns); - modules.add(STANDARD_MODULES.Relations); - modules.add(STANDARD_MODULES.Functions); - modules.add(STANDARD_MODULES.FunctionsAsRelations); - modules.add(STANDARD_MODULES.SequencesExtended); - modules.add(STANDARD_MODULES.SequencesAsRelations); - modules.add(STANDARD_MODULES.ExternalFunctions); - } - - private final Set<STANDARD_MODULES> extendedStandardModules; + modules.add(StandardModule.Naturals); + modules.add(StandardModule.Integers); + modules.add(StandardModule.FiniteSets); + modules.add(StandardModule.Sequences); + modules.add(StandardModule.TLC); + modules.add(StandardModule.BBuiltIns); + modules.add(StandardModule.Relations); + modules.add(StandardModule.Functions); + modules.add(StandardModule.FunctionsAsRelations); + modules.add(StandardModule.SequencesExtended); + modules.add(StandardModule.SequencesAsRelations); + modules.add(StandardModule.ExternalFunctions); + } + + private final Set<StandardModule> extendedStandardModules; private final Typechecker typechecker; public UsedStandardModules(Start start, Typechecker typechecker, TypeRestrictor typeRestrictor, TLAModule tlaModule) { - this.extendedStandardModules = new HashSet<STANDARD_MODULES>(); + this.extendedStandardModules = new HashSet<>(); this.typechecker = typechecker; if (TLC4BGlobals.useSymmetry()) { - extendedStandardModules.add(STANDARD_MODULES.TLC); + extendedStandardModules.add(StandardModule.TLC); } List<PDefinition> definitions = tlaModule.getAllDefinitions(); @@ -151,79 +149,75 @@ public class UsedStandardModules extends DepthFirstAdapter { start.apply(this); } - public ArrayList<STANDARD_MODULES> getExtendedModules() { - ArrayList<STANDARD_MODULES> list = new ArrayList<STANDARD_MODULES>( - extendedStandardModules); - if (list.contains(STANDARD_MODULES.Integers)) { - list.remove(STANDARD_MODULES.Naturals); + public List<String> getExtendedModules() { + ArrayList<StandardModule> list = new ArrayList<>(extendedStandardModules); + if (list.contains(StandardModule.Integers)) { + list.remove(StandardModule.Naturals); } - Collections.sort(list, new Comparator<STANDARD_MODULES>() { - public int compare(STANDARD_MODULES s1, STANDARD_MODULES s2) { - Integer i1 = Integer.valueOf(modules.indexOf(s1)); - Integer i2 = Integer.valueOf(modules.indexOf(s2)); - return i1.compareTo(i2); - } + list.sort((s1, s2) -> { + Integer i1 = modules.indexOf(s1); + Integer i2 = modules.indexOf(s2); + return i1.compareTo(i2); }); - return list; + return list.stream().map(StandardModule::name).collect(Collectors.toList()); } - public HashSet<STANDARD_MODULES> getStandardModulesToBeCreated() { + public Set<String> getStandardModulesToBeCreated() { // dependencies of standard modules - HashSet<STANDARD_MODULES> res = new HashSet<STANDARD_MODULES>(); - for (STANDARD_MODULES module : extendedStandardModules) { + HashSet<StandardModule> res = new HashSet<>(); + for (StandardModule module : extendedStandardModules) { switch (module) { case ExternalFunctions: - res.add(STANDARD_MODULES.ExternalFunctions); + res.add(StandardModule.ExternalFunctions); break; case FunctionsAsRelations: - res.add(STANDARD_MODULES.FunctionsAsRelations); - res.add(STANDARD_MODULES.Functions); + res.add(StandardModule.FunctionsAsRelations); + res.add(StandardModule.Functions); break; case SequencesAsRelations: - res.add(STANDARD_MODULES.SequencesAsRelations); - res.add(STANDARD_MODULES.Relations); - res.add(STANDARD_MODULES.FunctionsAsRelations); - res.add(STANDARD_MODULES.Functions); + res.add(StandardModule.SequencesAsRelations); + res.add(StandardModule.Relations); + res.add(StandardModule.FunctionsAsRelations); + res.add(StandardModule.Functions); break; case BBuiltIns: - res.add(STANDARD_MODULES.BBuiltIns); + res.add(StandardModule.BBuiltIns); break; case Functions: - res.add(STANDARD_MODULES.Functions); + res.add(StandardModule.Functions); break; case Relations: - res.add(STANDARD_MODULES.Relations); + res.add(StandardModule.Relations); break; case Sequences: break; case SequencesExtended: - res.add(STANDARD_MODULES.SequencesExtended); + res.add(StandardModule.SequencesExtended); break; default: break; } } - return res; + return res.stream().map(StandardModule::name).collect(Collectors.toSet()); } @Override - public void inAExpressionDefinitionDefinition( - AExpressionDefinitionDefinition node) { + public void inAExpressionDefinitionDefinition(AExpressionDefinitionDefinition node) { if (TLC4BGlobals.isForceTLCToEvalConstants()) { - extendedStandardModules.add(STANDARD_MODULES.TLC); + extendedStandardModules.add(StandardModule.TLC); } String name = node.getName().getText().trim(); - if (StandardMadules.isKeywordInModuleExternalFunctions(name)) { - extendedStandardModules.add(STANDARD_MODULES.ExternalFunctions); + if (StandardModules.isKeywordInModuleExternalFunctions(name)) { + extendedStandardModules.add(StandardModule.ExternalFunctions); } } @Override public void inADefinitionPredicate(ADefinitionPredicate node) { String name = node.getDefLiteral().getText().trim(); - if (StandardMadules.isKeywordInModuleExternalFunctions(name)) { - extendedStandardModules.add(STANDARD_MODULES.ExternalFunctions); + if (StandardModules.isKeywordInModuleExternalFunctions(name)) { + extendedStandardModules.add(StandardModule.ExternalFunctions); } } @@ -233,46 +227,46 @@ public class UsedStandardModules extends DepthFirstAdapter { @Override public void caseANaturalSetExpression(ANaturalSetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } @Override public void caseANatural1SetExpression(ANatural1SetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } @Override public void caseANatSetExpression(ANatSetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } @Override public void caseANat1SetExpression(ANat1SetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inALessEqualPredicate(ALessEqualPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inALessPredicate(ALessPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inAGreaterEqualPredicate(AGreaterEqualPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inAGreaterPredicate(AGreaterPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inAAddExpression(AAddExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } public void inAIntervalExpression(AIntervalExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } @@ -280,16 +274,16 @@ public class UsedStandardModules extends DepthFirstAdapter { AMinusOrSetSubtractExpression node) { BType t = typechecker.getType(node); if (t instanceof IntegerType) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } } public void inAMultOrCartExpression(AMultOrCartExpression node) { BType t = typechecker.getType(node); if (t instanceof IntegerType) { - extendedStandardModules.add(STANDARD_MODULES.Naturals); + extendedStandardModules.add(StandardModule.Naturals); } else { - // usedStandardModules.add(STANDARD_MODULES.RelationsNew); + // usedStandardModules.add(StandardModule.RelationsNew); } } @@ -298,26 +292,26 @@ public class UsedStandardModules extends DepthFirstAdapter { */ public void inAIntSetExpression(AIntSetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Integers); + extendedStandardModules.add(StandardModule.Integers); } public void inAIntegerSetExpression(AIntegerSetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Integers); + extendedStandardModules.add(StandardModule.Integers); } public void inAUnaryMinusExpression(AUnaryMinusExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Integers); + extendedStandardModules.add(StandardModule.Integers); } public void inAMinIntExpression(AMinIntExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Integers); + extendedStandardModules.add(StandardModule.Integers); } /** * FiniteSets */ public void inACardExpression(ACardExpression node) { - extendedStandardModules.add(STANDARD_MODULES.FiniteSets); + extendedStandardModules.add(StandardModule.FiniteSets); } /** @@ -325,73 +319,73 @@ public class UsedStandardModules extends DepthFirstAdapter { */ public void inAPowerOfExpression(APowerOfExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAMinExpression(AMinExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAMaxExpression(AMaxExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAModuloExpression(AModuloExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inADivExpression(ADivExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAGeneralSumExpression(AGeneralSumExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAGeneralProductExpression(AGeneralProductExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inASuccessorExpression(ASuccessorExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAPredecessorExpression(APredecessorExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAPow1SubsetExpression(APow1SubsetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAFinSubsetExpression(AFinSubsetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAFin1SubsetExpression(AFin1SubsetExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inANotSubsetPredicate(ANotSubsetPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inANotSubsetStrictPredicate(ANotSubsetStrictPredicate node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAGeneralIntersectionExpression( AGeneralIntersectionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAQuantifiedIntersectionExpression( AQuantifiedIntersectionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.BBuiltIns); + extendedStandardModules.add(StandardModule.BBuiltIns); } public void inAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { - // usedStandardModules.add(STANDARD_MODULES.BBuiltIns); + // usedStandardModules.add(StandardModule.BBuiltIns); } /** @@ -400,9 +394,9 @@ public class UsedStandardModules extends DepthFirstAdapter { private void setOfFunctions(Node node) { SetType set = (SetType) typechecker.getType(node); if (set.getSubtype() instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.Functions); + extendedStandardModules.add(StandardModule.Functions); } else { - extendedStandardModules.add(STANDARD_MODULES.FunctionsAsRelations); + extendedStandardModules.add(StandardModule.FunctionsAsRelations); } } @@ -451,7 +445,7 @@ public class UsedStandardModules extends DepthFirstAdapter { } BType type = typechecker.getType(node.getIdentifier()); if (type instanceof SetType) { - extendedStandardModules.add(STANDARD_MODULES.FunctionsAsRelations); + extendedStandardModules.add(StandardModule.FunctionsAsRelations); } } @@ -459,7 +453,7 @@ public class UsedStandardModules extends DepthFirstAdapter { public void inATotalFunctionExpression(ATotalFunctionExpression node) { SetType type = (SetType) typechecker.getType(node); if (type.getSubtype() instanceof SetType) { - extendedStandardModules.add(STANDARD_MODULES.FunctionsAsRelations); + extendedStandardModules.add(StandardModule.FunctionsAsRelations); } } @@ -470,27 +464,27 @@ public class UsedStandardModules extends DepthFirstAdapter { private void evalFunctionOrRelation(Node node) { BType t = typechecker.getType(node); if (t instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.Functions); + extendedStandardModules.add(StandardModule.Functions); } else { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } } public void inARelationsExpression(ARelationsExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inADomainExpression(ADomainExpression node) { BType t = typechecker.getType(node.getExpression()); if (!(t instanceof FunctionType)) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } } public void inASetExtensionExpression(ASetExtensionExpression node) { BType t = typechecker.getType(node); if (t instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.TLC); + extendedStandardModules.add(StandardModule.TLC); } } @@ -531,59 +525,58 @@ public class UsedStandardModules extends DepthFirstAdapter { } public void inAAssignSubstitution(AAssignSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getLhsExpression()); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); for (PExpression e : copy) { if (e instanceof AFunctionExpression) { BType type = typechecker.getType(((AFunctionExpression) e) .getIdentifier()); if (type instanceof SetType) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } else { - extendedStandardModules.add(STANDARD_MODULES.Functions); + extendedStandardModules.add(StandardModule.Functions); } } } } public void inADirectProductExpression(ADirectProductExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inAParallelProductExpression(AParallelProductExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inACompositionExpression(ACompositionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inAFirstProjectionExpression(AFirstProjectionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inASecondProjectionExpression(ASecondProjectionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inAIterationExpression(AIterationExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inAClosureExpression(AClosureExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inAReflexiveClosureExpression(AReflexiveClosureExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inATransFunctionExpression(ATransFunctionExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } public void inATransRelationExpression(ATransRelationExpression node) { - extendedStandardModules.add(STANDARD_MODULES.Relations); + extendedStandardModules.add(StandardModule.Relations); } /** @@ -593,9 +586,9 @@ public class UsedStandardModules extends DepthFirstAdapter { public void inASeqExpression(ASeqExpression node) { SetType type = (SetType) typechecker.getType(node); if (type.getSubtype() instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.Sequences); + extendedStandardModules.add(StandardModule.Sequences); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } @@ -610,9 +603,9 @@ public class UsedStandardModules extends DepthFirstAdapter { private void evalSequenceOrRelation(Node node) { BType type = typechecker.getType(node); if (type instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.Sequences); + extendedStandardModules.add(StandardModule.Sequences); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } @@ -631,36 +624,36 @@ public class UsedStandardModules extends DepthFirstAdapter { private void evalSequenceExtendedOrRelation(Node node) { BType type = typechecker.getType(node); if (type instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.SequencesExtended); + extendedStandardModules.add(StandardModule.SequencesExtended); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } public void inAIseqExpression(AIseqExpression node) { SetType set = (SetType) typechecker.getType(node); if (set.getSubtype() instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.SequencesExtended); + extendedStandardModules.add(StandardModule.SequencesExtended); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } public void inASeq1Expression(ASeq1Expression node) { SetType set = (SetType) typechecker.getType(node); if (set.getSubtype() instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.SequencesExtended); + extendedStandardModules.add(StandardModule.SequencesExtended); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } public void inAIseq1Expression(AIseq1Expression node) { SetType set = (SetType) typechecker.getType(node); if (set.getSubtype() instanceof FunctionType) { - extendedStandardModules.add(STANDARD_MODULES.SequencesExtended); + extendedStandardModules.add(StandardModule.SequencesExtended); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } } @@ -679,9 +672,9 @@ public class UsedStandardModules extends DepthFirstAdapter { public void inAPermExpression(APermExpression node) { SetType set = (SetType) typechecker.getType(node); if (set.getSubtype() instanceof SetType) { - extendedStandardModules.add(STANDARD_MODULES.SequencesAsRelations); + extendedStandardModules.add(StandardModule.SequencesAsRelations); } else { - extendedStandardModules.add(STANDARD_MODULES.SequencesExtended); + extendedStandardModules.add(StandardModule.SequencesExtended); } } diff --git a/src/main/java/de/tlc4b/analysis/transformation/DefinitionCollector.java b/src/main/java/de/tlc4b/analysis/transformation/DefinitionCollector.java index 57e8c3cacede24aaed24a810faa9ec12056207ca..ee05bf463a8eeee5c85ca5618fb1377f0a7be5bf 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/DefinitionCollector.java +++ b/src/main/java/de/tlc4b/analysis/transformation/DefinitionCollector.java @@ -23,11 +23,11 @@ import de.be4.classicalb.core.parser.node.Start; public class DefinitionCollector extends DepthFirstAdapter { - private Hashtable<String, PDefinition> definitionsTable; + private final Hashtable<String, PDefinition> definitionsTable; private ADefinitionsMachineClause definitionsMachineClause; public Hashtable<String, PDefinition> getDefinitions() { - return new Hashtable<String, PDefinition>(definitionsTable); + return new Hashtable<>(definitionsTable); } public ADefinitionsMachineClause getDefinitionsMachineClause() { @@ -35,7 +35,7 @@ public class DefinitionCollector extends DepthFirstAdapter { } public DefinitionCollector(Start tree) { - definitionsTable = new Hashtable<String, PDefinition>(); + definitionsTable = new Hashtable<>(); tree.apply(this); } @@ -47,19 +47,19 @@ public class DefinitionCollector extends DepthFirstAdapter { @Override public void caseAPredicateDefinitionDefinition( APredicateDefinitionDefinition node) { - definitionsTable.put(node.getName().getText().toString(), node); + definitionsTable.put(node.getName().getText(), node); } @Override public void caseASubstitutionDefinitionDefinition( ASubstitutionDefinitionDefinition node) { - definitionsTable.put(node.getName().getText().toString(), node); + definitionsTable.put(node.getName().getText(), node); } @Override public void caseAExpressionDefinitionDefinition( AExpressionDefinitionDefinition node) { - definitionsTable.put(node.getName().getText().toString(), node); + definitionsTable.put(node.getName().getText(), node); } /*************************************************************************** diff --git a/src/main/java/de/tlc4b/analysis/transformation/DefinitionsEliminator.java b/src/main/java/de/tlc4b/analysis/transformation/DefinitionsEliminator.java index c872e28c92bc150f52e2291f1e6dab64daf54a0c..4837b2b3bc425abdc7f18f7ab36f9a4ba89034bc 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/DefinitionsEliminator.java +++ b/src/main/java/de/tlc4b/analysis/transformation/DefinitionsEliminator.java @@ -20,13 +20,13 @@ import de.be4.classicalb.core.parser.node.PExpression; import de.be4.classicalb.core.parser.node.PMachineClause; import de.be4.classicalb.core.parser.node.Start; import de.be4.classicalb.core.parser.util.Utils; -import de.tlc4b.analysis.StandardMadules; +import de.tlc4b.analysis.StandardModules; /** * This class eliminates all definition calls in the MACHINE. A definition call * will be replaced by the right-hand side of the definition and all parameter * on the RHS are replaced by the arguments of the call. - * + * <p> * Note: All parameters of a definition are replaced before a call of a * sub-definition is resolved. This behavior is similar to what ProB does when * eliminating all definitions. @@ -34,8 +34,8 @@ import de.tlc4b.analysis.StandardMadules; */ public class DefinitionsEliminator extends DepthFirstAdapter { - private Hashtable<String, PDefinition> definitionsTable; - private ArrayList<Hashtable<String, PExpression>> contextStack; + private final Hashtable<String, PDefinition> definitionsTable; + private final ArrayList<Hashtable<String, PExpression>> contextStack; public static void eliminateDefinitions(Start start){ new DefinitionsEliminator(start); @@ -44,7 +44,7 @@ public class DefinitionsEliminator extends DepthFirstAdapter { private DefinitionsEliminator(Start node) { DefinitionCollector collector = new DefinitionCollector(node); definitionsTable = collector.getDefinitions(); - contextStack = new ArrayList<Hashtable<String, PExpression>>(); + contextStack = new ArrayList<>(); node.apply(this); } @@ -58,29 +58,27 @@ public class DefinitionsEliminator extends DepthFirstAdapter { defClause = (ADefinitionsMachineClause) e; } } - if (defClause != null && defClause.getDefinitions().size() == 0) { + if (defClause != null && defClause.getDefinitions().isEmpty()) { defClause.replaceBy(null); } } @Override public void caseADefinitionsMachineClause(ADefinitionsMachineClause node) { - /** + /* * Definitions from other definitions files were injected into the * DefinitionsCLause. However, their parent was not correctly set to the * DefinitionsClause. Hence e.replaceBy(null) would not eliminate them. * Therefore, we have to create a new list and have to the use the * setDefinitions method form {link ADefinitionsMachineClause}. - **/ + */ - List<PDefinition> newDefinitionsList = new ArrayList<PDefinition>(); - List<PDefinition> oldDefinitionsList = new ArrayList<PDefinition>( - node.getDefinitions()); + List<PDefinition> newDefinitionsList = new ArrayList<>(); + List<PDefinition> oldDefinitionsList = new ArrayList<>(node.getDefinitions()); for (PDefinition e : oldDefinitionsList) { // replace all definitions calls inside the definitions bodies if (e instanceof AExpressionDefinitionDefinition) { - String name = ((AExpressionDefinitionDefinition) e).getName() - .getText().toString(); + String name = ((AExpressionDefinitionDefinition) e).getName().getText(); if (Utils.isProBSpecialDefinitionName(name)) continue; } @@ -90,29 +88,22 @@ public class DefinitionsEliminator extends DepthFirstAdapter { // add certain definitions to the new definitions list in order to // obtain them for the translation for (PDefinition e : oldDefinitionsList) { - if (e instanceof AExpressionDefinitionDefinition) { - - String name = ((AExpressionDefinitionDefinition) e).getName() - .getText().toString(); + String name = ((AExpressionDefinitionDefinition) e).getName().getText(); if (Utils.isProBSpecialDefinitionName(name) - || StandardMadules - .isKeywordInModuleExternalFunctions(name)) { - + || StandardModules.isKeywordInModuleExternalFunctions(name)) { newDefinitionsList.add(e); } } else if (e instanceof APredicateDefinitionDefinition) { - String name = ((APredicateDefinitionDefinition) e).getName() - .getText().toString(); + String name = ((APredicateDefinitionDefinition) e).getName().getText(); if (Utils.isProBSpecialDefinitionName(name) - || StandardMadules - .isKeywordInModuleExternalFunctions(name)) { + || StandardModules.isKeywordInModuleExternalFunctions(name)) { newDefinitionsList.add(e); } } } for (PDefinition def : newDefinitionsList) { - // we have delete all parents of the definitions in order to set + // we have deleted all parents of the definitions in order to set // them in the next step (seems to be a bug in SabbleCC) def.replaceBy(null); } @@ -124,11 +115,9 @@ public class DefinitionsEliminator extends DepthFirstAdapter { String name = node.getDefLiteral().getText(); PDefinition def = definitionsTable.get(name); - ASubstitutionDefinitionDefinition clone = (ASubstitutionDefinitionDefinition) def - .clone(); - Hashtable<String, PExpression> context = new Hashtable<String, PExpression>(); - ArrayList<PExpression> arguments = new ArrayList<PExpression>( - node.getParameters()); + ASubstitutionDefinitionDefinition clone = (ASubstitutionDefinitionDefinition) def.clone(); + Hashtable<String, PExpression> context = new Hashtable<>(); + ArrayList<PExpression> arguments = new ArrayList<>(node.getParameters()); for (int i = 0; i < clone.getParameters().size(); i++) { AIdentifierExpression p = (AIdentifierExpression) clone .getParameters().get(i); @@ -147,9 +136,8 @@ public class DefinitionsEliminator extends DepthFirstAdapter { @Override public void caseADefinitionExpression(ADefinitionExpression node) { String name = node.getDefLiteral().getText(); - ArrayList<PExpression> arguments = new ArrayList<PExpression>( - node.getParameters()); - if (StandardMadules.isKeywordInModuleExternalFunctions(name)) { + ArrayList<PExpression> arguments = new ArrayList<>(node.getParameters()); + if (StandardModules.isKeywordInModuleExternalFunctions(name)) { for (PExpression arg : arguments) { arg.apply(this); } @@ -157,13 +145,11 @@ public class DefinitionsEliminator extends DepthFirstAdapter { } PDefinition def = definitionsTable.get(name); - AExpressionDefinitionDefinition clone = (AExpressionDefinitionDefinition) def - .clone(); - Hashtable<String, PExpression> context = new Hashtable<String, PExpression>(); + AExpressionDefinitionDefinition clone = (AExpressionDefinitionDefinition) def.clone(); + Hashtable<String, PExpression> context = new Hashtable<>(); for (int i = 0; i < clone.getParameters().size(); i++) { - AIdentifierExpression p = (AIdentifierExpression) clone - .getParameters().get(i); + AIdentifierExpression p = (AIdentifierExpression) clone.getParameters().get(i); String paramName = Utils.getTIdentifierListAsString(p.getIdentifier()); Node arg = arguments.get(i); arg.apply(this); @@ -180,22 +166,19 @@ public class DefinitionsEliminator extends DepthFirstAdapter { String name = node.getDefLiteral().getText(); PDefinition def = definitionsTable.get(name); - ArrayList<PExpression> arguments = new ArrayList<PExpression>( - node.getParameters()); - if (StandardMadules.isKeywordInModuleExternalFunctions(name)) { + ArrayList<PExpression> arguments = new ArrayList<>(node.getParameters()); + if (StandardModules.isKeywordInModuleExternalFunctions(name)) { for (PExpression arg : arguments) { arg.apply(this); } return; } - APredicateDefinitionDefinition clone = (APredicateDefinitionDefinition) def - .clone(); - Hashtable<String, PExpression> context = new Hashtable<String, PExpression>(); + APredicateDefinitionDefinition clone = (APredicateDefinitionDefinition) def.clone(); + Hashtable<String, PExpression> context = new Hashtable<>(); for (int i = 0; i < clone.getParameters().size(); i++) { - AIdentifierExpression p = (AIdentifierExpression) clone - .getParameters().get(i); + AIdentifierExpression p = (AIdentifierExpression) clone.getParameters().get(i); String paramName = Utils.getTIdentifierListAsString(p.getIdentifier()); Node arg = arguments.get(i); @@ -206,13 +189,12 @@ public class DefinitionsEliminator extends DepthFirstAdapter { contextStack.add(context); clone.getRhs().apply(this); node.replaceBy(clone.getRhs()); - contextStack.remove(context); } @Override public void caseAIdentifierExpression(AIdentifierExpression node) { - if (contextStack.size() == 0) + if (contextStack.isEmpty()) return; String name = Utils.getTIdentifierListAsString(node.getIdentifier()); @@ -220,7 +202,7 @@ public class DefinitionsEliminator extends DepthFirstAdapter { Hashtable<String, PExpression> context = contextStack.get(i); PExpression e = context.get(name); if (e != null) { - node.replaceBy((PExpression) e.clone()); + node.replaceBy(e.clone()); } } } diff --git a/src/main/java/de/tlc4b/analysis/transformation/DefinitionsSorter.java b/src/main/java/de/tlc4b/analysis/transformation/DefinitionsSorter.java index 8061e7c03b8f8e5dbe773241407d025c297007af..d9616642dcda3b0a4aebb16c4c65579e3a8bce24 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/DefinitionsSorter.java +++ b/src/main/java/de/tlc4b/analysis/transformation/DefinitionsSorter.java @@ -2,7 +2,6 @@ package de.tlc4b.analysis.transformation; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; @@ -23,10 +22,10 @@ public class DefinitionsSorter extends DepthFirstAdapter { String current = null; public DefinitionsSorter(ADefinitionsMachineClause clause) { - dependencies = new LinkedHashMap<String, HashSet<String>>(); - allDependencies = new LinkedHashMap<String, HashSet<String>>(); - definitionsTable = new LinkedHashMap<String, PDefinition>(); - res = new ArrayList<PDefinition>(); + dependencies = new LinkedHashMap<>(); + allDependencies = new LinkedHashMap<>(); + definitionsTable = new LinkedHashMap<>(); + res = new ArrayList<>(); clause.apply(this); @@ -34,19 +33,16 @@ public class DefinitionsSorter extends DepthFirstAdapter { resolveDependencies(defName); } - ArrayList<String> defs = new ArrayList<String>(allDependencies.keySet()); + ArrayList<String> defs = new ArrayList<>(allDependencies.keySet()); while (!res.containsAll(definitionsTable.values())) { - Iterator<String> iterator = new ArrayList<String>(defs).iterator(); - while (iterator.hasNext()) { - String next = iterator.next(); - + for (String next : new ArrayList<>(defs)) { HashSet<String> deps = allDependencies.get(next); - + deps.retainAll(defs); - - if (deps.size() == 0) { + + if (deps.isEmpty()) { PDefinition pDefinition = definitionsTable.get(next); pDefinition.replaceBy(null); res.add(pDefinition); @@ -62,7 +58,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { if (allDependencies.containsKey(defName)) { return; } - HashSet<String> allDeps = new HashSet<String>(); + HashSet<String> allDeps = new HashSet<>(); HashSet<String> deps = dependencies.get(defName); for (String def : deps) { resolveDependencies(def); @@ -81,7 +77,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { @Override public void inAPredicateDefinitionDefinition( APredicateDefinitionDefinition node) { - String name = node.getName().getText().toString(); + String name = node.getName().getText(); addDefinition(name); definitionsTable.put(name, node); current = name; @@ -90,7 +86,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { @Override public void inASubstitutionDefinitionDefinition( ASubstitutionDefinitionDefinition node) { - String name = node.getName().getText().toString(); + String name = node.getName().getText(); addDefinition(name); definitionsTable.put(name, node); current = name; @@ -99,7 +95,7 @@ public class DefinitionsSorter extends DepthFirstAdapter { @Override public void inAExpressionDefinitionDefinition( AExpressionDefinitionDefinition node) { - String name = node.getName().getText().toString(); + String name = node.getName().getText(); addDefinition(name); definitionsTable.put(name, node); current = name; @@ -107,25 +103,25 @@ public class DefinitionsSorter extends DepthFirstAdapter { @Override public void inADefinitionExpression(ADefinitionExpression node) { - String name = node.getDefLiteral().getText().toString(); + String name = node.getDefLiteral().getText(); addDefinitionCall(name); } @Override public void inADefinitionPredicate(ADefinitionPredicate node) { - String name = node.getDefLiteral().getText().toString(); + String name = node.getDefLiteral().getText(); addDefinitionCall(name); } @Override public void inADefinitionSubstitution(ADefinitionSubstitution node) { - String name = node.getDefLiteral().getText().toString(); + String name = node.getDefLiteral().getText(); addDefinitionCall(name); } private void addDefinition(String name) { - if (!dependencies.keySet().contains(name)) { - dependencies.put(name, new HashSet<String>()); + if (!dependencies.containsKey(name)) { + dependencies.put(name, new HashSet<>()); } } diff --git a/src/main/java/de/tlc4b/analysis/transformation/MachineClauseSorter.java b/src/main/java/de/tlc4b/analysis/transformation/MachineClauseSorter.java index 98ea212bce3f8a25d12afc481a80b228c403667b..c9b4cbefde97cb8f6123c6e5a7cb2d40c1b447a9 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/MachineClauseSorter.java +++ b/src/main/java/de/tlc4b/analysis/transformation/MachineClauseSorter.java @@ -1,7 +1,6 @@ package de.tlc4b.analysis.transformation; import java.io.Serializable; -import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.LinkedList; @@ -36,13 +35,13 @@ public class MachineClauseSorter extends DepthFirstAdapter { LinkedList<PMachineClause> machineClauses = node.getMachineClauses(); - PMachineClauseComparator comperator = new PMachineClauseComparator(); + PMachineClauseComparator comparator = new PMachineClauseComparator(); // Sort the machine clauses: // 1. import clauses // 2. declaration clauses // 3. properties clauses // 4. operation clauses - Collections.sort(machineClauses, comperator); + machineClauses.sort(comparator); } } @@ -50,7 +49,7 @@ class PMachineClauseComparator implements Comparator<PMachineClause>, Serializable { private static final long serialVersionUID = 2606332412649258695L; - private static Hashtable<Object, Integer> priority = new Hashtable<Object, Integer>(); + private static final Hashtable<Object, Integer> priority = new Hashtable<>(); static { // declarations clauses @@ -72,16 +71,7 @@ class PMachineClauseComparator implements Comparator<PMachineClause>, } public int compare(PMachineClause arg0, PMachineClause arg1) { - if (priority.get(arg0.getClass()).intValue() < priority.get( - arg1.getClass()).intValue()) { - return 1; - } - if (priority.get(arg0.getClass()).intValue() > priority.get( - arg1.getClass()).intValue()) { - return -1; - } - - return 0; + return priority.get(arg1.getClass()).compareTo(priority.get(arg0.getClass())); } } \ No newline at end of file diff --git a/src/main/java/de/tlc4b/analysis/transformation/SeesEliminator.java b/src/main/java/de/tlc4b/analysis/transformation/SeesEliminator.java index aa51bfa00aae1b1d3336b88f06865bb29ce78e50..2ec908b5d6960ad821275f94ba24fc4695c72f92 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/SeesEliminator.java +++ b/src/main/java/de/tlc4b/analysis/transformation/SeesEliminator.java @@ -24,7 +24,6 @@ import de.be4.classicalb.core.parser.node.PParseUnit; import de.be4.classicalb.core.parser.node.PPredicate; import de.be4.classicalb.core.parser.node.Start; import de.be4.classicalb.core.parser.util.Utils; -import de.tlc4b.TLC4BGlobals; public class SeesEliminator extends DepthFirstAdapter { @@ -32,19 +31,16 @@ public class SeesEliminator extends DepthFirstAdapter { private final Map<String, Start> parsedMachines; private final ArrayList<String> resolvedMachines; - public static void eliminateSeesClauses(Start start, - Map<String, Start> parsedMachines) { - new SeesEliminator(start, parsedMachines, new ArrayList<String>()); + public static void eliminateSeesClauses(Start start, Map<String, Start> parsedMachines) { + new SeesEliminator(start, parsedMachines, new ArrayList<>()); } - private void eliminateSeenMachinesRecursively(Start start, - Map<String, Start> parsedMachines, - ArrayList<String> resolvedMachines) { + private void eliminateSeenMachinesRecursively(Start start, Map<String, Start> parsedMachines, + ArrayList<String> resolvedMachines) { new SeesEliminator(start, parsedMachines, resolvedMachines); } - private SeesEliminator(Start start, Map<String, Start> parsedMachines, - ArrayList<String> resolvedMachines) { + private SeesEliminator(Start start, Map<String, Start> parsedMachines, ArrayList<String> resolvedMachines) { this.main = start; this.parsedMachines = parsedMachines; this.resolvedMachines = resolvedMachines; @@ -55,14 +51,12 @@ public class SeesEliminator extends DepthFirstAdapter { public void inASeesMachineClause(ASeesMachineClause node) { for (PMachineReferenceNoParams pExpression : node.getMachineNames()) { AMachineReferenceNoParams id = (AMachineReferenceNoParams) pExpression; - String machineName = Utils - .getTIdentifierListAsString(id.getMachineName()); + String machineName = Utils.getTIdentifierListAsString(id.getMachineName()); if (!resolvedMachines.contains(machineName)) { resolvedMachines.add(machineName); Start start = parsedMachines.get(machineName); DefinitionsEliminator.eliminateDefinitions(start); - eliminateSeenMachinesRecursively(start, parsedMachines, - resolvedMachines); + eliminateSeenMachinesRecursively(start, parsedMachines, resolvedMachines); new MachineClauseAdder(main, start); if (node.parent() != null) { node.replaceBy(null); @@ -71,29 +65,26 @@ public class SeesEliminator extends DepthFirstAdapter { } } - class MachineClauseAdder extends DepthFirstAdapter { - private final ArrayList<PMachineClause> machineClausesList; + static class MachineClauseAdder extends DepthFirstAdapter { private final HashMap<Class<? extends PMachineClause>, PMachineClause> machineClauseHashMap; private final LinkedList<PMachineClause> additionalMachineClauseList; public MachineClauseAdder(Start main, Start seenMachineStart) { - this.machineClausesList = new ArrayList<PMachineClause>(); - this.machineClauseHashMap = new LinkedHashMap<Class<? extends PMachineClause>, PMachineClause>(); - this.additionalMachineClauseList = new LinkedList<PMachineClause>(); + ArrayList<PMachineClause> machineClausesList = new ArrayList<>(); + this.machineClauseHashMap = new LinkedHashMap<>(); + this.additionalMachineClauseList = new LinkedList<>(); PParseUnit pParseUnit = main.getPParseUnit(); AAbstractMachineParseUnit machineParseUnit = (AAbstractMachineParseUnit) pParseUnit; - for (PMachineClause machineClause : machineParseUnit - .getMachineClauses()) { + for (PMachineClause machineClause : machineParseUnit.getMachineClauses()) { machineClausesList.add(machineClause); - machineClauseHashMap.put(machineClause.getClass(), - machineClause); + machineClauseHashMap.put(machineClause.getClass(), machineClause); } seenMachineStart.apply(this); - LinkedList<PMachineClause> newMachineClauseList = new LinkedList<PMachineClause>(); + LinkedList<PMachineClause> newMachineClauseList = new LinkedList<>(); for (PMachineClause pMachineClause : machineClausesList) { pMachineClause.replaceBy(null); // delete parent of clause newMachineClauseList.add(pMachineClause); @@ -104,46 +95,38 @@ public class SeesEliminator extends DepthFirstAdapter { @Override public void caseAConstantsMachineClause(AConstantsMachineClause node) { - AConstantsMachineClause main = (AConstantsMachineClause) machineClauseHashMap - .get(node.getClass()); + AConstantsMachineClause main = (AConstantsMachineClause) machineClauseHashMap.get(node.getClass()); if (main == null) { additionalMachineClauseList.add(node); } else { - ArrayList<PExpression> oldConstantsList = new ArrayList<PExpression>( - main.getIdentifiers()); - ArrayList<PExpression> newConstantsList = new ArrayList<PExpression>(); + ArrayList<PExpression> oldConstantsList = new ArrayList<>(main.getIdentifiers()); + ArrayList<PExpression> newConstantsList = new ArrayList<>(); for (PExpression pExpression : oldConstantsList) { pExpression.replaceBy(null); // delete parent newConstantsList.add(pExpression); } - ArrayList<PExpression> otherConstants = new ArrayList<PExpression>( - node.getIdentifiers()); + ArrayList<PExpression> otherConstants = new ArrayList<>(node.getIdentifiers()); for (PExpression pExpression : otherConstants) { pExpression.replaceBy(null); // delete parent newConstantsList.add(pExpression); - } main.setIdentifiers(newConstantsList); } } - public void caseAAbstractConstantsMachineClause( - AAbstractConstantsMachineClause node) { - AAbstractConstantsMachineClause main = (AAbstractConstantsMachineClause) machineClauseHashMap - .get(node.getClass()); + public void caseAAbstractConstantsMachineClause(AAbstractConstantsMachineClause node) { + AAbstractConstantsMachineClause main = (AAbstractConstantsMachineClause) machineClauseHashMap.get(node.getClass()); if (main != null) { - ArrayList<PExpression> oldConstantsList = new ArrayList<PExpression>( - main.getIdentifiers()); - ArrayList<PExpression> newConstantsList = new ArrayList<PExpression>(); + ArrayList<PExpression> oldConstantsList = new ArrayList<>(main.getIdentifiers()); + ArrayList<PExpression> newConstantsList = new ArrayList<>(); for (PExpression pExpression : oldConstantsList) { pExpression.replaceBy(null); // delete parent newConstantsList.add(pExpression); } - ArrayList<PExpression> otherConstants = new ArrayList<PExpression>( - node.getIdentifiers()); + ArrayList<PExpression> otherConstants = new ArrayList<>(node.getIdentifiers()); for (PExpression pExpression : otherConstants) { pExpression.replaceBy(null); // delete parent @@ -159,8 +142,7 @@ public class SeesEliminator extends DepthFirstAdapter { @Override public void caseAPropertiesMachineClause(APropertiesMachineClause node) { - APropertiesMachineClause main = (APropertiesMachineClause) machineClauseHashMap - .get(node.getClass()); + APropertiesMachineClause main = (APropertiesMachineClause) machineClauseHashMap.get(node.getClass()); if (main == null) { additionalMachineClauseList.add(node); } else { @@ -174,21 +156,18 @@ public class SeesEliminator extends DepthFirstAdapter { @Override public void caseADefinitionsMachineClause(ADefinitionsMachineClause node) { - ADefinitionsMachineClause main = (ADefinitionsMachineClause) machineClauseHashMap - .get(node.getClass()); + ADefinitionsMachineClause main = (ADefinitionsMachineClause) machineClauseHashMap.get(node.getClass()); if (main == null) { additionalMachineClauseList.add(node); } else { - ArrayList<PDefinition> oldDefinitions = new ArrayList<PDefinition>( - main.getDefinitions()); - ArrayList<PDefinition> newDefinitionsList = new ArrayList<PDefinition>(); + ArrayList<PDefinition> oldDefinitions = new ArrayList<>(main.getDefinitions()); + ArrayList<PDefinition> newDefinitionsList = new ArrayList<>(); for (PDefinition pExpression : oldDefinitions) { pExpression.replaceBy(null); // delete parent newDefinitionsList.add(pExpression); } - ArrayList<PDefinition> otherConstants = new ArrayList<PDefinition>( - node.getDefinitions()); + ArrayList<PDefinition> otherConstants = new ArrayList<>(node.getDefinitions()); for (PDefinition definition : otherConstants) { if (definition.parent() != null) { @@ -202,22 +181,17 @@ public class SeesEliminator extends DepthFirstAdapter { } public void caseAAssertionsMachineClause(AAssertionsMachineClause node) { - if (TLC4BGlobals.isCheckOnlyMainAssertions()) - return; - AAssertionsMachineClause main = (AAssertionsMachineClause) machineClauseHashMap - .get(node.getClass()); + AAssertionsMachineClause main = (AAssertionsMachineClause) machineClauseHashMap.get(node.getClass()); if (main == null) { additionalMachineClauseList.add(node); } else { - ArrayList<PPredicate> old = new ArrayList<PPredicate>( - main.getPredicates()); - ArrayList<PPredicate> newList = new ArrayList<PPredicate>(); + ArrayList<PPredicate> old = new ArrayList<>(main.getPredicates()); + ArrayList<PPredicate> newList = new ArrayList<>(); for (PPredicate p : old) { p.replaceBy(null); // delete parent newList.add(p); } - ArrayList<PPredicate> otherAssertions = new ArrayList<PPredicate>( - node.getPredicates()); + ArrayList<PPredicate> otherAssertions = new ArrayList<>(node.getPredicates()); for (PPredicate p : otherAssertions) { if (p.parent() != null) { @@ -228,8 +202,6 @@ public class SeesEliminator extends DepthFirstAdapter { } main.setPredicates(newList); } - } - } } diff --git a/src/main/java/de/tlc4b/analysis/transformation/SequenceSubstitutionsEliminator.java b/src/main/java/de/tlc4b/analysis/transformation/SequenceSubstitutionsEliminator.java new file mode 100644 index 0000000000000000000000000000000000000000..6daf1c0711ca6b97d359a950b538593b8ad69650 --- /dev/null +++ b/src/main/java/de/tlc4b/analysis/transformation/SequenceSubstitutionsEliminator.java @@ -0,0 +1,248 @@ +package de.tlc4b.analysis.transformation; + +import de.be4.classicalb.core.parser.analysis.DepthFirstAdapter; +import de.be4.classicalb.core.parser.node.*; +import de.tlc4b.exceptions.NotSupportedException; + +import java.util.*; +import java.util.stream.Collectors; + +import static de.tlc4b.MP.printlnVerbose; + +/** + * Replace all SequenceSubstitutions by ParallelSubstitutions. + * Replace sequentially assigned identifiers by primed identifiers, + * e.g. x := 1 ; y := x will be translated to x' = 1 /\ y' = x'. + * Whether the assignments are still valid is checked later by the AssignedVariablesFinder + * and UnchangedVariablesFinder, which are called by the Translator. + */ +public class SequenceSubstitutionsEliminator extends DepthFirstAdapter { + + private enum SubstitutionMode { + PARALLEL, + SEQUENTIAL + } + + private ASequenceSubstitution topLevel = null; + private boolean initialisationMode = false, replacementMode = false; + + private final Set<List<String>> parallelAssignedVariables = new HashSet<>(); + private final Set<List<String>> currentAssignedVariables = new HashSet<>(); + private final Deque<SubstitutionMode> modeStack = new ArrayDeque<>(); + private final Set<Node> primeNodes = new HashSet<>(); + + public SequenceSubstitutionsEliminator(Start start) { + start.apply(this); + } + + @Override + public void inAAnySubstitution(AAnySubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getWhere().apply(this); + replacementMode = false; + } + + @Override + public void inAAssertionSubstitution(AAssertionSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getPredicate().apply(this); + replacementMode = false; + } + + @Override + public void inAAssignSubstitution(AAssignSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + for (PExpression rhs : node.getRhsExpressions()) { + rhs.apply(this); + } + replacementMode = false; + + for (PExpression lhs : node.getLhsExpression()) { + if (lhs instanceof AIdentifierExpression) { + assignVariables((AIdentifierExpression) lhs); + } else if (lhs instanceof AFunctionExpression) { + // TODO: what to do with AFunctionExpression? + throw new NotSupportedException("function assignments in sequential substitutions are not yet supported"); + } + } + } + + @Override + public void inABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getSet().apply(this); + replacementMode = false; + + for (PExpression lhs : node.getIdentifiers()) { + if (lhs instanceof AIdentifierExpression) { + assignVariables((AIdentifierExpression) lhs); + } + } + } + + @Override + public void inABecomesSuchSubstitution(ABecomesSuchSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getPredicate().apply(this); + replacementMode = false; + + for (PExpression lhs : node.getIdentifiers()) { + if (lhs instanceof AIdentifierExpression) { + assignVariables((AIdentifierExpression) lhs); + } + } + } + + @Override + public void caseAIdentifierExpression(AIdentifierExpression node) { + if (topLevel == null) + return; + + // mark identifiers that have already been assigned in the current block as primed + if (!initialisationMode && replacementMode && currentAssignedVariables.contains(identifierToStringList(node))) { + primeNodes.add(node); + } + } + + @Override + public void inAIfSubstitution(AIfSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getCondition().apply(this); + replacementMode = false; + } + + @Override + public void inAIfElsifSubstitution(AIfElsifSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getCondition().apply(this); + replacementMode = false; + } + + @Override + public void inAInitialisationMachineClause(AInitialisationMachineClause node) { + initialisationMode = true; + } + + @Override + public void outAInitialisationMachineClause(AInitialisationMachineClause node) { + initialisationMode = false; + } + + @Override + public void inALetSubstitution(ALetSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getPredicate().apply(this); + replacementMode = false; + } + + @Override + public void inAParallelSubstitution(AParallelSubstitution node) { + modeStack.push(SubstitutionMode.PARALLEL); + } + + @Override + public void outAParallelSubstitution(AParallelSubstitution node) { + if (modeStack.removeFirst() != SubstitutionMode.PARALLEL) { + throw new IllegalStateException("expected PARALLEL mode"); + } + + if (modeStack.peekFirst() == SubstitutionMode.SEQUENTIAL) { + currentAssignedVariables.addAll(parallelAssignedVariables); + parallelAssignedVariables.clear(); + } + } + + @Override + public void inAPreconditionSubstitution(APreconditionSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getPredicate().apply(this); + replacementMode = false; + } + + @Override + public void inASelectSubstitution(ASelectSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getCondition().apply(this); + replacementMode = false; + } + + @Override + public void inASelectWhenSubstitution(ASelectWhenSubstitution node) { + if (topLevel == null) + return; + + replacementMode = true; + node.getCondition().apply(this); + replacementMode = false; + } + + @Override + public void inASequenceSubstitution(ASequenceSubstitution node) { + if (topLevel == null) { + topLevel = node; + } + modeStack.push(SubstitutionMode.SEQUENTIAL); + } + + @Override + public void outASequenceSubstitution(ASequenceSubstitution node) { + node.replaceBy(new AParallelSubstitution(new ArrayList<>(node.getSubstitutions()))); + printlnVerbose(node.getStartPos() + "-" + node.getEndPos() + ": replaced sequential substitution by parallel substitution"); + + if (modeStack.pollFirst() != SubstitutionMode.SEQUENTIAL) { + throw new IllegalStateException("expected SEQUENTIAL mode"); + } + + if (topLevel.equals(node)) { + topLevel = null; + parallelAssignedVariables.clear(); + currentAssignedVariables.clear(); + } + } + + private void assignVariables(AIdentifierExpression lhs) { + if (modeStack.peekFirst() == SubstitutionMode.SEQUENTIAL) { + currentAssignedVariables.add(identifierToStringList(lhs)); + } else if (modeStack.peekFirst() == SubstitutionMode.PARALLEL) { + parallelAssignedVariables.add(identifierToStringList(lhs)); + } + } + + private static List<String> identifierToStringList(AIdentifierExpression identifier) { + return identifier.getIdentifier().stream().map(Token::getText).collect(Collectors.toList()); + } + + public Set<Node> getPrimeNodes() { + return primeNodes; + } +} diff --git a/src/main/java/de/tlc4b/analysis/transformation/SetComprehensionOptimizer.java b/src/main/java/de/tlc4b/analysis/transformation/SetComprehensionOptimizer.java index 5dd60e094f33b63e4f87e58a462eb0dfb28981a4..46628e367a19a64abacfd886273f50855a75b7e3 100644 --- a/src/main/java/de/tlc4b/analysis/transformation/SetComprehensionOptimizer.java +++ b/src/main/java/de/tlc4b/analysis/transformation/SetComprehensionOptimizer.java @@ -44,18 +44,17 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { public void caseAComprehensionSetExpression(AComprehensionSetExpression node) { final LinkedList<PExpression> identifiers = node.getIdentifiers(); - final ArrayList<String> list = new ArrayList<String>(); - final Hashtable<String, AIdentifierExpression> identifierTable = new Hashtable<String, AIdentifierExpression>(); - for (int i = 0; i < identifiers.size(); i++) { - AIdentifierExpression id = (AIdentifierExpression) identifiers - .get(i); + final ArrayList<String> list = new ArrayList<>(); + final Hashtable<String, AIdentifierExpression> identifierTable = new Hashtable<>(); + for (PExpression identifier : identifiers) { + AIdentifierExpression id = (AIdentifierExpression) identifier; String name = Utils.getTIdentifierListAsString(id.getIdentifier()); list.add(name); identifierTable.put(name, id); } - Hashtable<String, PExpression> values = new Hashtable<String, PExpression>(); - ArrayList<AEqualPredicate> equalList = new ArrayList<AEqualPredicate>(); + Hashtable<String, PExpression> values = new Hashtable<>(); + ArrayList<AEqualPredicate> equalList = new ArrayList<>(); analysePredicate(node.getPredicates(), list, values, equalList); ArrayList<ADomainExpression> parentDomainExprsList = collectParentDomainExpression(node @@ -73,7 +72,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { // If these conditions are not fulfilled, the AST transformation will // not be applied. // However, other optimization techniques may be applicable. - if ((values.size() > 0 || parentDomainExprsList.size() > 0) + if ((!values.isEmpty() || !parentDomainExprsList.isEmpty()) && values.size() < list.size() && list.size() - values.size() <= 2) { @@ -84,10 +83,10 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { int exprCount = list.size() - max; // {ids. ids2 \in {ids3 \in S: P } | exprs} - ArrayList<PExpression> ids = new ArrayList<PExpression>(); - ArrayList<PExpression> ids2 = new ArrayList<PExpression>(); - ArrayList<PExpression> ids3 = new ArrayList<PExpression>(); - ArrayList<PExpression> exprs = new ArrayList<PExpression>(); + ArrayList<PExpression> ids = new ArrayList<>(); + ArrayList<PExpression> ids2 = new ArrayList<>(); + ArrayList<PExpression> ids3 = new ArrayList<>(); + ArrayList<PExpression> exprs = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { String name = list.get(i); @@ -96,7 +95,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { if (values.containsKey(name)) { exprs.add(values.get(name)); } else { - PExpression clone = (PExpression) identifierTable.get( + PExpression clone = identifierTable.get( name).clone(); exprs.add(clone); } @@ -104,13 +103,13 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { // remaining quantified variables if (!values.containsKey(name)) { - PExpression clone = (PExpression) identifierTable.get(name) + PExpression clone = identifierTable.get(name) .clone(); ids.add(clone); - PExpression clone2 = (PExpression) identifierTable + PExpression clone2 = identifierTable .get(name).clone(); ids2.add(clone2); - PExpression clone3 = (PExpression) identifierTable + PExpression clone3 = identifierTable .get(name).clone(); ids3.add(clone3); } @@ -135,7 +134,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { eventBcomprehension.setPredicates(member); setSourcePosition(node, eventBcomprehension); - if (parentDomainExprsList.size() > 0) { + if (!parentDomainExprsList.isEmpty()) { ADomainExpression aDomainExpression = parentDomainExprsList .get(max - 1); aDomainExpression.replaceBy(eventBcomprehension); @@ -166,7 +165,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { domExprList.add(0, (ADomainExpression) node); return domExprList; } else { - return new ArrayList<ADomainExpression>(); + return new ArrayList<>(); } } @@ -190,7 +189,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { AIdentifierExpression id = (AIdentifierExpression) equal .getLeft(); String name = Utils.getTIdentifierListAsString(id.getIdentifier()); - Set<String> names = new HashSet<String>(values.keySet()); + Set<String> names = new HashSet<>(values.keySet()); names.add(name); if (list.contains(name) && !DependenciesDetector.expressionContainsIdentifier( @@ -203,7 +202,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { AIdentifierExpression id = (AIdentifierExpression) equal .getRight(); String name = Utils.getTIdentifierListAsString(id.getIdentifier()); - Set<String> names = new HashSet<String>(values.keySet()); + Set<String> names = new HashSet<>(values.keySet()); names.add(name); if (list.contains(name) && !DependenciesDetector.expressionContainsIdentifier( @@ -233,8 +232,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { } } - static boolean expressionContainsIdentifier(PExpression node, - Set<String> names) { + static boolean expressionContainsIdentifier(PExpression node, Set<String> names) { DependenciesDetector dependenciesDetector = new DependenciesDetector( names); node.apply(dependenciesDetector); @@ -243,7 +241,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { } - class NodesRemover extends DepthFirstAdapter { + static class NodesRemover extends DepthFirstAdapter { final ArrayList<AEqualPredicate> removeList; final Hashtable<String, PExpression> values; @@ -292,7 +290,7 @@ public class SetComprehensionOptimizer extends DepthFirstAdapter { // todo the name is not a unique of the node PExpression value = values.get(name); if (value != null) { - node.replaceBy((PExpression) value.clone()); + node.replaceBy(value.clone()); } } diff --git a/src/main/java/de/tlc4b/analysis/typerestriction/IdentifierDependencies.java b/src/main/java/de/tlc4b/analysis/typerestriction/IdentifierDependencies.java index e4b9f595bc773c9f501bca2726a9e2056564159c..b986ce0871e98ef4de7a0bd2c3322a988c5abefa 100644 --- a/src/main/java/de/tlc4b/analysis/typerestriction/IdentifierDependencies.java +++ b/src/main/java/de/tlc4b/analysis/typerestriction/IdentifierDependencies.java @@ -16,7 +16,7 @@ public class IdentifierDependencies extends DepthFirstAdapter { public IdentifierDependencies(MachineContext machineContext) { this.machineContext = machineContext; - this.usedIdentifier = new HashMap<Node, HashSet<Node>>(); + this.usedIdentifier = new HashMap<>(); } @@ -42,7 +42,7 @@ public class IdentifierDependencies extends DepthFirstAdapter { Node refNode = machineContext.getReferenceNode(node); if(refNode == null) refNode = node; - HashSet<Node> set = new HashSet<Node>(); + HashSet<Node> set = new HashSet<>(); set.add(refNode); setSetToNode(node, set); @@ -52,7 +52,7 @@ public class IdentifierDependencies extends DepthFirstAdapter { private void setSetToNode(Node node, HashSet<Node> set) { HashSet<Node> oldSet = usedIdentifier.get(node); if (oldSet == null) { - oldSet = new HashSet<Node>(); + oldSet = new HashSet<>(); } if (set != null) { oldSet.addAll(set); diff --git a/src/main/java/de/tlc4b/analysis/typerestriction/TypeRestrictor.java b/src/main/java/de/tlc4b/analysis/typerestriction/TypeRestrictor.java index b6b2648804fef658b29c7e1a3510ab8413383879..479abd532fecaa8a83f1cd20b2370cc3ae426a9e 100644 --- a/src/main/java/de/tlc4b/analysis/typerestriction/TypeRestrictor.java +++ b/src/main/java/de/tlc4b/analysis/typerestriction/TypeRestrictor.java @@ -82,11 +82,11 @@ public class TypeRestrictor extends DepthFirstAdapter { this.typechecker = typechecker; this.constantsEvaluator = constantsEvaluator; - this.restrictedTypeNodeTable = new Hashtable<Node, Node>(); - this.removedNodes = new HashSet<Node>(); + this.restrictedTypeNodeTable = new Hashtable<>(); + this.removedNodes = new HashSet<>(); - this.restrictedNodeTable = new Hashtable<Node, ArrayList<Node>>(); - this.subtractedNodeTable = new Hashtable<Node, ArrayList<Node>>(); + this.restrictedNodeTable = new Hashtable<>(); + this.subtractedNodeTable = new Hashtable<>(); this.identifierDependencies = new IdentifierDependencies(machineContext); @@ -103,26 +103,24 @@ public class TypeRestrictor extends DepthFirstAdapter { Node bNode = visitor.getBAst(ltlNode); if (ltlNode instanceof AExistsLtl) { - Node id = visitor.getLTLIdentifier(((AExistsLtl) ltlNode) + PExpression id = visitor.getLTLIdentifier(((AExistsLtl) ltlNode) .getExistsIdentifier().getText()); - HashSet<Node> list = new HashSet<Node>(); + HashSet<Node> list = new HashSet<>(); list.add(id); - analysePredicate(bNode, list, new HashSet<Node>()); + analysePredicate(bNode, list, new HashSet<>()); - PExpression e = (PExpression) id; - HashSet<PExpression> set = new HashSet<PExpression>(); - set.add(e); + HashSet<PExpression> set = new HashSet<>(); + set.add(id); createRestrictedTypeofLocalVariables(set, true); } else if (ltlNode instanceof AForallLtl) { - Node id = visitor.getLTLIdentifier(((AForallLtl) ltlNode) + PExpression id = visitor.getLTLIdentifier(((AForallLtl) ltlNode) .getForallIdentifier().getText()); - HashSet<Node> list = new HashSet<Node>(); + HashSet<Node> list = new HashSet<>(); list.add(id); - analysePredicate(bNode, list, new HashSet<Node>()); + analysePredicate(bNode, list, new HashSet<>()); - PExpression e = (PExpression) id; - HashSet<PExpression> set = new HashSet<PExpression>(); - set.add(e); + HashSet<PExpression> set = new HashSet<>(); + set.add(id); createRestrictedTypeofLocalVariables(set, true); } bNode.apply(this); @@ -139,7 +137,7 @@ public class TypeRestrictor extends DepthFirstAdapter { ArrayList<Node> list = restrictedNodeTable.get(identifier); if (list == null) { - list = new ArrayList<Node>(); + list = new ArrayList<>(); list.add(expression); restrictedNodeTable.put(identifier, list); } else { @@ -149,10 +147,10 @@ public class TypeRestrictor extends DepthFirstAdapter { } } - private void putSubstractedType(Node identifier, Node expression) { + private void putSubtractedType(Node identifier, Node expression) { ArrayList<Node> list = subtractedNodeTable.get(identifier); if (list == null) { - list = new ArrayList<Node>(); + list = new ArrayList<>(); list.add(expression); subtractedNodeTable.put(identifier, list); } else { @@ -162,36 +160,30 @@ public class TypeRestrictor extends DepthFirstAdapter { @Override public void inAConstraintsMachineClause(AConstraintsMachineClause node) { - HashSet<Node> list = new HashSet<Node>(); - // list.addAll(machineContext.getSetParamter().values()); - list.addAll(machineContext.getScalarParameter().values()); - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - HashSet<PExpression> set = new HashSet<PExpression>(); + // list.addAll(machineContext.getSetParameter().values()); + HashSet<Node> list = new HashSet<>(machineContext.getScalarParameter().values()); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + HashSet<PExpression> set = new HashSet<>(); for (Node param : list) { set.add((PExpression) param); } - createRestrictedTypeofLocalVariables(new HashSet<PExpression>(set), - false); + createRestrictedTypeofLocalVariables(new HashSet<>(set), false); } @Override public void inAPropertiesMachineClause(APropertiesMachineClause node) { - HashSet<PExpression> set = new HashSet<PExpression>(); + HashSet<PExpression> set = new HashSet<>(); for (Node con : machineContext.getConstants().values()) { set.add((PExpression) con); Node valueOfConstant = constantsEvaluator.getValueOfConstant(con); - if(valueOfConstant!= null){ + if (valueOfConstant != null) { removedNodes.add(valueOfConstant.parent()); } - } - HashSet<Node> list = new HashSet<Node>(); - list.addAll(machineContext.getConstants().values()); - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - + HashSet<Node> list = new HashSet<>(machineContext.getConstants().values()); + analysePredicate(node.getPredicates(), list, new HashSet<>()); - createRestrictedTypeofLocalVariables(new HashSet<PExpression>(set), - false); + createRestrictedTypeofLocalVariables(new HashSet<>(set), false); } public void analyseDisjunktionPredicate(PPredicate node, HashSet<Node> list) { @@ -200,12 +192,11 @@ public class TypeRestrictor extends DepthFirstAdapter { analyseDisjunktionPredicate(dis.getLeft(), list); analyseDisjunktionPredicate(dis.getRight(), list); } else { - analysePredicate(node, list, new HashSet<Node>()); + analysePredicate(node, list, new HashSet<>()); } } - private void analysePredicate(Node n, HashSet<Node> list, - HashSet<Node> ignoreList) { + private void analysePredicate(Node n, HashSet<Node> list, HashSet<Node> ignoreList) { if (removedNodes.contains(n)) return; @@ -219,9 +210,9 @@ public class TypeRestrictor extends DepthFirstAdapter { if (list.contains(r_left) && isAConstantExpression(right, list, ignoreList)) { right.apply(this); - ArrayList<PExpression> element = new ArrayList<PExpression>(); + ArrayList<PExpression> element = new ArrayList<>(); element.add(right); - if (machineContext.getVariables().values().contains(r_left)) { + if (machineContext.getVariables().containsValue(r_left)) { r_left = variablesHashTable.get(r_left); } putRestrictedType(r_left, new ASetExtensionExpression(element)); @@ -230,9 +221,9 @@ public class TypeRestrictor extends DepthFirstAdapter { if (list.contains(r_right) && isAConstantExpression(left, list, ignoreList)) { left.apply(this); - ArrayList<PExpression> element = new ArrayList<PExpression>(); + ArrayList<PExpression> element = new ArrayList<>(); element.add(left); - if (machineContext.getVariables().values().contains(r_right)) { + if (machineContext.getVariables().containsValue(r_right)) { r_right = variablesHashTable.get(r_right); } putRestrictedType(r_right, new ASetExtensionExpression(element)); @@ -265,7 +256,7 @@ public class TypeRestrictor extends DepthFirstAdapter { PExpression right = ((AMemberPredicate) n).getRight(); if (list.contains(r_left) && isAConstantExpression(right, list, ignoreList)) { - if (machineContext.getVariables().values().contains(r_left)) { + if (machineContext.getVariables().containsValue(r_left)) { r_left = variablesHashTable.get(r_left); } putRestrictedType(r_left, right); @@ -280,10 +271,10 @@ public class TypeRestrictor extends DepthFirstAdapter { PExpression right = ((ANotMemberPredicate) n).getRight(); if (list.contains(r_left) && isAConstantExpression(right, list, ignoreList)) { - if (machineContext.getVariables().values().contains(r_left)) { + if (machineContext.getVariables().containsValue(r_left)) { r_left = variablesHashTable.get(r_left); } - putSubstractedType(r_left, right); + putSubtractedType(r_left, right); removedNodes.add(n); } return; @@ -297,7 +288,7 @@ public class TypeRestrictor extends DepthFirstAdapter { if (list.contains(r_left) && isAConstantExpression(right, list, ignoreList)) { right.apply(this); - if (machineContext.getVariables().values().contains(r_left)) { + if (machineContext.getVariables().containsValue(r_left)) { r_left = variablesHashTable.get(r_left); } putRestrictedType(r_left, new APowSubsetExpression(right)); @@ -318,10 +309,8 @@ public class TypeRestrictor extends DepthFirstAdapter { } if (n instanceof AExistsPredicate) { - HashSet<Node> set = new HashSet<Node>(); - for (PExpression e : ((AExistsPredicate) n).getIdentifiers()) { - set.add(e); - } + HashSet<Node> set = new HashSet<>(); + set.addAll(((AExistsPredicate) n).getIdentifiers()); set.addAll(ignoreList); analysePredicate(((AExistsPredicate) n).getPredicate(), list, set); } @@ -333,145 +322,94 @@ public class TypeRestrictor extends DepthFirstAdapter { if (n instanceof APredicateParseUnit) { analysePredicate(((APredicateParseUnit) n).getPredicate(), list, ignoreList); - return; } } public boolean isAConstantExpression(Node node, HashSet<Node> list, HashSet<Node> ignoreList) { - HashSet<Node> newList = new HashSet<Node>(); + HashSet<Node> newList = new HashSet<>(); newList.addAll(list); newList.addAll(ignoreList); - if (identifierDependencies.containsIdentifier(node, newList)) { - return false; - } - return true; + return !identifierDependencies.containsIdentifier(node, newList); } @Override public void inAForallPredicate(AForallPredicate node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - AImplicationPredicate implication = (AImplicationPredicate) node - .getImplication(); - analysePredicate(implication.getLeft(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + AImplicationPredicate implication = (AImplicationPredicate) node.getImplication(); + analysePredicate(implication.getLeft(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override public void inAExistsPredicate(AExistsPredicate node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicate(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicate(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override public void inAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override - public void inAQuantifiedIntersectionExpression( - AQuantifiedIntersectionExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + public void inAQuantifiedIntersectionExpression(AQuantifiedIntersectionExpression node) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override public void inAComprehensionSetExpression(AComprehensionSetExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override public void inALambdaExpression(ALambdaExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicate(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicate(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } public void inAGeneralSumExpression(AGeneralSumExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } public void inAGeneralProductExpression(AGeneralProductExpression node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } - analysePredicate(node.getPredicates(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(copy); + analysePredicate(node.getPredicates(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } - private Hashtable<Node, HashSet<PExpression>> expectedIdentifieListTable = new Hashtable<Node, HashSet<PExpression>>(); + private final Hashtable<Node, HashSet<PExpression>> expectedIdentifieListTable = new Hashtable<>(); @Override - public void caseAInitialisationMachineClause( - AInitialisationMachineClause node) { - expectedIdentifieListTable.put(node.getSubstitutions(), - new HashSet<PExpression>()); + public void caseAInitialisationMachineClause(AInitialisationMachineClause node) { + expectedIdentifieListTable.put(node.getSubstitutions(), new HashSet<>()); node.getSubstitutions().apply(this); } @Override public void caseAOperation(AOperation node) { - HashSet<PExpression> list = new HashSet<PExpression>(); + HashSet<PExpression> list = new HashSet<>(); { - List<PExpression> copy = new ArrayList<PExpression>( - node.getParameters()); - for (PExpression e : copy) { - list.add(e); - } + List<PExpression> copy = new ArrayList<>(node.getParameters()); + list.addAll(copy); } expectedIdentifieListTable.put(node.getOperationBody(), list); if (node.getOperationBody() != null) { @@ -482,74 +420,63 @@ public class TypeRestrictor extends DepthFirstAdapter { @Override public void inAPreconditionSubstitution(APreconditionSubstitution node) { - HashSet<Node> set = new HashSet<Node>(getExpectedIdentifier(node)); - analysePredicate(node.getPredicate(), set, new HashSet<Node>()); + HashSet<Node> set = new HashSet<>(getExpectedIdentifier(node)); + analysePredicate(node.getPredicate(), set, new HashSet<>()); } private HashSet<PExpression> getExpectedIdentifier(Node node) { HashSet<PExpression> list = expectedIdentifieListTable.get(node); if (list == null) - list = new HashSet<PExpression>(); + list = new HashSet<>(); return list; } @Override public void inASelectSubstitution(ASelectSubstitution node) { - HashSet<Node> list = new HashSet<Node>(getExpectedIdentifier(node)); - analysePredicate(node.getCondition(), list, new HashSet<Node>()); + HashSet<Node> list = new HashSet<>(getExpectedIdentifier(node)); + analysePredicate(node.getCondition(), list, new HashSet<>()); } @Override public void inAAnySubstitution(AAnySubstitution node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } + HashSet<Node> list = new HashSet<>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + list.addAll(copy); list.addAll(getExpectedIdentifier(node)); - analysePredicate(node.getWhere(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + analysePredicate(node.getWhere(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } @Override public void inALetSubstitution(ALetSubstitution node) { - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - list.add(e); - } + HashSet<Node> list = new HashSet<>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + list.addAll(copy); list.addAll(getExpectedIdentifier(node)); - analysePredicate(node.getPredicate(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(node.getIdentifiers()), false); + analysePredicate(node.getPredicate(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(node.getIdentifiers()), false); } private Hashtable<Node, Node> variablesHashTable; public void inABecomesSuchSubstitution(ABecomesSuchSubstitution node) { if (!(node.getPredicate() instanceof AExistsPredicate)) { - variablesHashTable = new Hashtable<Node, Node>(); + variablesHashTable = new Hashtable<>(); - HashSet<Node> list = new HashSet<Node>(); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (PExpression e : copy) { Node ref = machineContext.getReferenceNode(e); list.add(ref); variablesHashTable.put(ref, e); } - analysePredicate(node.getPredicate(), list, new HashSet<Node>()); - createRestrictedTypeofLocalVariables( - new HashSet<PExpression>(copy), false); + analysePredicate(node.getPredicate(), list, new HashSet<>()); + createRestrictedTypeofLocalVariables(new HashSet<>(copy), false); } } - private void createRestrictedTypeofLocalVariables(Set<PExpression> copy, - boolean constant) { + private void createRestrictedTypeofLocalVariables(Set<PExpression> copy, boolean constant) { // TODO if constant is true, only constant expressions should be used to // restrict the type. // This is required by the TLC model checker when checking an LTL @@ -560,20 +487,18 @@ public class TypeRestrictor extends DepthFirstAdapter { continue; } - PExpression tree = null; + PExpression tree; ArrayList<Node> restrictedList = restrictedNodeTable.get(e); if (restrictedList == null) { BType conType = typechecker.getType(e); if (conType == null) { - conType = typechecker.getType(machineContext - .getReferenceNode(e)); + conType = typechecker.getType(machineContext.getReferenceNode(e)); } if (conType.containsInfiniteType() && !(e.parent() instanceof ALambdaExpression) && !(e.parent() instanceof AComprehensionSetExpression)) { AIdentifierExpression id = (AIdentifierExpression) e; - String localVariableName = Utils.getTIdentifierListAsString(id - .getIdentifier()); + String localVariableName = Utils.getTIdentifierListAsString(id.getIdentifier()); throw new NotSupportedException( "Unable to restrict the type '" + conType @@ -592,12 +517,11 @@ public class TypeRestrictor extends DepthFirstAdapter { } } - ArrayList<Node> substractedList = subtractedNodeTable.get(e); - if (substractedList != null) { - for (int i = 0; i < substractedList.size(); i++) { - PExpression n = (PExpression) substractedList.get(i); + ArrayList<Node> subtractedList = subtractedNodeTable.get(e); + if (subtractedList != null) { + for (Node node : subtractedList) { + PExpression n = (PExpression) node; tree = new ASetSubtractionExpression(tree, n); - } } this.restrictedTypeNodeTable.put(e, tree); @@ -607,8 +531,7 @@ public class TypeRestrictor extends DepthFirstAdapter { @Override public void caseAAssertionsMachineClause(AAssertionsMachineClause node) { if (TLC4BGlobals.isAssertion()) { - List<PPredicate> copy = new ArrayList<PPredicate>( - node.getPredicates()); + List<PPredicate> copy = new ArrayList<>(node.getPredicates()); for (PPredicate e : copy) { e.apply(this); } diff --git a/src/main/java/de/tlc4b/analysis/unchangedvariables/AssignedVariablesFinder.java b/src/main/java/de/tlc4b/analysis/unchangedvariables/AssignedVariablesFinder.java index 0b82cc59b410404a46f2cd73b0904b46d86bdc58..efde0eec729cb1c8b34848e83526c92efc7fee52 100644 --- a/src/main/java/de/tlc4b/analysis/unchangedvariables/AssignedVariablesFinder.java +++ b/src/main/java/de/tlc4b/analysis/unchangedvariables/AssignedVariablesFinder.java @@ -34,7 +34,7 @@ import de.tlc4b.exceptions.SubstitutionException; /** * * This class is a tree walker which searches for all assigned variables in a - * branch of a operation body. The algorithm works in a bottom up style. The + * branch of an operation body. The algorithm works in a bottom up style. The * {@link assignedVariablesTable} will finally contain all assigned variables * for a node. For example a {@link AParallelSubstitution} node will get a list * of all assigned variables of its children. Operation output parameter are @@ -47,7 +47,7 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { private final MachineContext machineContext; public AssignedVariablesFinder(MachineContext machineContext) { - this.assignedVariablesTable = new Hashtable<Node, HashSet<Node>>(); + this.assignedVariablesTable = new Hashtable<>(); this.machineContext = machineContext; machineContext.getStartNode().apply(this); @@ -65,9 +65,9 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { public void defaultOut(final Node node) { /* * This case is important if the parent node is not visited by the - * visitor. The assigned variables are transfered up in the tree. e.g. + * visitor. The assigned variables are transferred up in the tree. e.g. * if the parent node is a block substitution, the assigned variables - * are transfered to parent of the block substitution + * are transferred to parent of the block substitution */ HashSet<Node> assignedVariables = assignedVariablesTable.get(node); if (null != assignedVariables) { @@ -102,14 +102,11 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { /* * In the INITIALISATION clause all variables must be assigned. */ - HashSet<Node> allVariables = new HashSet<Node>(machineContext - .getVariables().values()); - HashSet<Node> foundVariables = new HashSet<Node>( - getVariableList(node.getSubstitutions())); + HashSet<Node> allVariables = new HashSet<>(machineContext.getVariables().values()); + HashSet<Node> foundVariables = new HashSet<>(getVariableList(node.getSubstitutions())); if (allVariables.retainAll(foundVariables)) { - HashSet<Node> missingVariables = new HashSet<Node>(machineContext - .getVariables().values()); + HashSet<Node> missingVariables = new HashSet<>(machineContext.getVariables().values()); missingVariables.removeAll(allVariables); throw new SubstitutionException( "Initialisation Error: Missing assignment for variable(s): " @@ -120,9 +117,8 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseABecomesSuchSubstitution(ABecomesSuchSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - HashSet<Node> list = new HashSet<Node>(); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(); for (PExpression e : copy) { Node identifier = machineContext.getReferenceNode(e); list.add(identifier); @@ -132,17 +128,15 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { } public void caseAAssignSubstitution(AAssignSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getLhsExpression()); - HashSet<Node> list = new HashSet<Node>(); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); + HashSet<Node> list = new HashSet<>(); for (PExpression e : copy) { if (e instanceof AIdentifierExpression) { Node identifier = machineContext.getReferenceNode(e); list.add(identifier); } else { AFunctionExpression func = (AFunctionExpression) e; - Node identifier = machineContext.getReferenceNode( - func.getIdentifier()); + Node identifier = machineContext.getReferenceNode(func.getIdentifier()); list.add(identifier); } } @@ -151,12 +145,9 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { } @Override - public void caseABecomesElementOfSubstitution( - ABecomesElementOfSubstitution node) { - - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - HashSet<Node> list = new HashSet<Node>(); + public void caseABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + HashSet<Node> list = new HashSet<>(); for (PExpression e : copy) { Node identifier = machineContext.getReferenceNode(e); list.add(identifier); @@ -167,9 +158,8 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseAChoiceSubstitution(AChoiceSubstitution node) { - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getSubstitutions()); - HashSet<Node> list = new HashSet<Node>(); + List<PSubstitution> copy = new ArrayList<>(node.getSubstitutions()); + HashSet<Node> list = new HashSet<>(); for (PSubstitution e : copy) { e.apply(this); list.addAll(getVariableList(e)); @@ -181,19 +171,16 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseAChoiceOrSubstitution(AChoiceOrSubstitution node) { node.getSubstitution().apply(this); - assignedVariablesTable.put(node, - getVariableList(node.getSubstitution())); + assignedVariablesTable.put(node, getVariableList(node.getSubstitution())); defaultOut(node); } @Override public void caseAIfSubstitution(AIfSubstitution node) { - HashSet<Node> list = new HashSet<Node>(); node.getThen().apply(this); - list.addAll(getVariableList(node.getThen())); + HashSet<Node> list = new HashSet<>(getVariableList(node.getThen())); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getElsifSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getElsifSubstitutions()); for (PSubstitution e : copy) { e.apply(this); list.addAll(getVariableList(e)); @@ -209,9 +196,8 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseAIfElsifSubstitution(AIfElsifSubstitution node) { - HashSet<Node> list = new HashSet<Node>(); node.getThenSubstitution().apply(this); - list.addAll(getVariableList(node.getThenSubstitution())); + HashSet<Node> list = new HashSet<>(getVariableList(node.getThenSubstitution())); assignedVariablesTable.put(node, list); defaultOut(node); @@ -219,17 +205,16 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseAParallelSubstitution(AParallelSubstitution node) { - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getSubstitutions()); for (PSubstitution e : copy) { e.apply(this); } - HashSet<Node> list = new HashSet<Node>(); + HashSet<Node> list = new HashSet<>(); for (PSubstitution e : copy) { HashSet<Node> listOfe = getVariableList(e); - HashSet<Node> temp = new HashSet<Node>(list); + HashSet<Node> temp = new HashSet<>(list); temp.retainAll(listOfe); - if (temp.size() > 0) { + if (!temp.isEmpty()) { throw new SubstitutionException("The variable(s) " + temp + " are assigned twice"); } @@ -241,11 +226,9 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseASelectSubstitution(ASelectSubstitution node) { - HashSet<Node> list = new HashSet<Node>(); node.getThen().apply(this); - list.addAll(getVariableList(node.getThen())); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getWhenSubstitutions()); + HashSet<Node> list = new HashSet<>(getVariableList(node.getThen())); + List<PSubstitution> copy = new ArrayList<>(node.getWhenSubstitutions()); for (PSubstitution e : copy) { e.apply(this); list.addAll(getVariableList(e)); @@ -261,16 +244,13 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseASelectWhenSubstitution(ASelectWhenSubstitution node) { node.getSubstitution().apply(this); - assignedVariablesTable.put(node, - getVariableList(node.getSubstitution())); - assignedVariablesTable.put(node.parent(), - getVariableList(node.getSubstitution())); + assignedVariablesTable.put(node, getVariableList(node.getSubstitution())); + assignedVariablesTable.put(node.parent(), getVariableList(node.getSubstitution())); } @Override public void caseADefinitionsMachineClause(ADefinitionsMachineClause node) { - List<PDefinition> copy = new ArrayList<PDefinition>( - node.getDefinitions()); + List<PDefinition> copy = new ArrayList<>(node.getDefinitions()); for (PDefinition e : copy) { e.apply(this); } @@ -286,7 +266,7 @@ public class AssignedVariablesFinder extends DepthFirstAdapter { @Override public void caseASkipSubstitution(ASkipSubstitution node) { - HashSet<Node> list = new HashSet<Node>(); + HashSet<Node> list = new HashSet<>(); assignedVariablesTable.put(node, list); defaultOut(node); } diff --git a/src/main/java/de/tlc4b/analysis/unchangedvariables/InvariantPreservationAnalysis.java b/src/main/java/de/tlc4b/analysis/unchangedvariables/InvariantPreservationAnalysis.java index 44c877744672f56626e3be58e6bd3575de3db281..4dfe3d62d8e86ed4e28212968246db75502c8095 100644 --- a/src/main/java/de/tlc4b/analysis/unchangedvariables/InvariantPreservationAnalysis.java +++ b/src/main/java/de/tlc4b/analysis/unchangedvariables/InvariantPreservationAnalysis.java @@ -20,31 +20,31 @@ public class InvariantPreservationAnalysis extends DepthFirstAdapter { private HashSet<Node> foundVariables; public ArrayList<Node> getPreservingOperations(Node invariant) { - return new ArrayList<Node>(preservingOperationsTable.get(invariant)); + return new ArrayList<>(preservingOperationsTable.get(invariant)); } public InvariantPreservationAnalysis(MachineContext machineContext, ArrayList<Node> invariants, UnchangedVariablesFinder unchangedFinder) { - this.foundVariablesTable = new Hashtable<Node, HashSet<Node>>(); + this.foundVariablesTable = new Hashtable<>(); this.machineContext = machineContext; - this.preservingOperationsTable = new Hashtable<Node, HashSet<Node>>(); + this.preservingOperationsTable = new Hashtable<>(); for (Node inv : invariants) { - foundVariables = new HashSet<Node>(); + foundVariables = new HashSet<>(); inv.apply(this); foundVariablesTable.put(inv, foundVariables); } for (Node inv : invariants) { - HashSet<Node> preservingOperations = new HashSet<Node>(); + HashSet<Node> preservingOperations = new HashSet<>(); HashSet<Node> usedVariables = foundVariablesTable.get(inv); for (Node op : machineContext.getOperations().values()) { HashSet<Node> assignedVariables = unchangedFinder .getAssignedVariables(op); - HashSet<Node> temp = new HashSet<Node>(usedVariables); + HashSet<Node> temp = new HashSet<>(usedVariables); temp.retainAll(assignedVariables); - if (temp.size() == 0) { + if (temp.isEmpty()) { preservingOperations.add(op); } } diff --git a/src/main/java/de/tlc4b/analysis/unchangedvariables/UnchangedVariablesFinder.java b/src/main/java/de/tlc4b/analysis/unchangedvariables/UnchangedVariablesFinder.java index d1d453ba1918e0babacc2631740cffc6e8e75c79..4b9095b80eda09a557fe85983b708d5e2b1369e4 100644 --- a/src/main/java/de/tlc4b/analysis/unchangedvariables/UnchangedVariablesFinder.java +++ b/src/main/java/de/tlc4b/analysis/unchangedvariables/UnchangedVariablesFinder.java @@ -33,7 +33,7 @@ import de.tlc4b.exceptions.SubstitutionException; /** * This class is a tree walker which calculates all missing variables - * assignments for each node inside a operation body. Missing variables + * assignments for each node inside an operation body. Missing variables * assignments correspond to unchanged variables in TLA+. B definitions or the * initialisation are not visited by this class. */ @@ -64,10 +64,7 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { if(set== null){ return false; }else{ - if(set.size() == 0){ - return false; - }else - return true; + return !set.isEmpty(); } } @@ -81,11 +78,11 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { AssignedVariablesFinder aVF = new AssignedVariablesFinder(c); this.assignedIdentifiersTable = aVF.getAssignedVariablesTable(); - this.expectedVariablesTable = new Hashtable<Node, HashSet<Node>>(); - this.expectedOutputParametersTable = new Hashtable<Node, HashSet<Node>>(); + this.expectedVariablesTable = new Hashtable<>(); + this.expectedOutputParametersTable = new Hashtable<>(); - this.unchangedVariablesTable = new Hashtable<Node, HashSet<Node>>(); - this.unchangedVariablesNull = new Hashtable<Node, HashSet<Node>>(); + this.unchangedVariablesTable = new Hashtable<>(); + this.unchangedVariablesNull = new Hashtable<>(); c.getStartNode().apply(this); } @@ -101,17 +98,12 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { @Override public void caseAOperation(AOperation node) { - HashSet<Node> expectedOutputParameter = new HashSet<Node>(); - List<PExpression> returnValues = new ArrayList<PExpression>( - node.getReturnValues()); - for (PExpression e : returnValues) { - expectedOutputParameter.add(e); - } + List<PExpression> returnValues = new ArrayList<>(node.getReturnValues()); + HashSet<Node> expectedOutputParameter = new HashSet<>(returnValues); Node body = node.getOperationBody(); expectedOutputParametersTable.put(body, expectedOutputParameter); - expectedVariablesTable.put(body, new HashSet<Node>(machineContext - .getVariables().values())); + expectedVariablesTable.put(body, new HashSet<>(machineContext.getVariables().values())); body.apply(this); @@ -120,15 +112,13 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { private void check(Node node) { HashSet<Node> found = assignedIdentifiersTable.get(node); - HashSet<Node> missingVariables = new HashSet<Node>( - expectedVariablesTable.get(node)); + HashSet<Node> missingVariables = new HashSet<>(expectedVariablesTable.get(node)); missingVariables.removeAll(found); unchangedVariablesTable.put(node, missingVariables); - HashSet<Node> missingOutputParameter = new HashSet<Node>( - expectedOutputParametersTable.get(node)); + HashSet<Node> missingOutputParameter = new HashSet<>(expectedOutputParametersTable.get(node)); missingOutputParameter.removeAll(found); - if (missingOutputParameter.size() > 0) { + if (!missingOutputParameter.isEmpty()) { throw new SubstitutionException( "To the following output parameters no values are assigned: " + missingOutputParameter); @@ -146,8 +136,7 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { } @Override - public void caseABecomesElementOfSubstitution( - ABecomesElementOfSubstitution node) { + public void caseABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { check(node); } @@ -155,12 +144,10 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { public void caseAParallelSubstitution(AParallelSubstitution node) { check(node); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getSubstitutions()); for (PSubstitution e : copy) { - - expectedOutputParametersTable.put(e, new HashSet<Node>()); - expectedVariablesTable.put(e, new HashSet<Node>()); + expectedOutputParametersTable.put(e, new HashSet<>()); + expectedVariablesTable.put(e, new HashSet<>()); e.apply(this); } } @@ -169,8 +156,8 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { public void caseAAnySubstitution(AAnySubstitution node) { check(node); - expectedOutputParametersTable.put(node.getThen(), new HashSet<Node>()); - expectedVariablesTable.put(node.getThen(), new HashSet<Node>()); + expectedOutputParametersTable.put(node.getThen(), new HashSet<>()); + expectedVariablesTable.put(node.getThen(), new HashSet<>()); node.getThen().apply(this); } @@ -178,9 +165,8 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { public void caseALetSubstitution(ALetSubstitution node) { check(node); - expectedOutputParametersTable.put(node.getSubstitution(), - new HashSet<Node>()); - expectedVariablesTable.put(node.getSubstitution(), new HashSet<Node>()); + expectedOutputParametersTable.put(node.getSubstitution(), new HashSet<>()); + expectedVariablesTable.put(node.getSubstitution(), new HashSet<>()); node.getSubstitution().apply(this); } @@ -190,18 +176,17 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { // Separating variables and output parameters HashSet<Node> foundIdentifiers = assignedIdentifiersTable.get(node); - HashSet<Node> variables = new HashSet<Node>(foundIdentifiers); + HashSet<Node> variables = new HashSet<>(foundIdentifiers); variables.removeAll(expectedOutputParametersTable.get(node)); // System.out.println(parameters); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getSubstitutions()); + List<PSubstitution> copy = new ArrayList<>( + node.getSubstitutions()); for (PSubstitution e : copy) { // each child of CHOICE must assign all variables and all output // parameter - expectedOutputParametersTable.put(e, - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(e, expectedOutputParametersTable.get(node)); expectedVariablesTable.put(e, variables); e.apply(this); } @@ -210,14 +195,12 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { @Override public void caseAChoiceOrSubstitution(AChoiceOrSubstitution node) { Node sub = node.getSubstitution(); - expectedOutputParametersTable.put(sub, - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(sub, expectedOutputParametersTable.get(node)); expectedVariablesTable.put(sub, expectedVariablesTable.get(node)); sub.apply(this); unchangedVariablesTable.put(node, unchangedVariablesTable.get(sub)); - } @Override @@ -225,41 +208,34 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { check(node); // Separating variables and output parameters HashSet<Node> foundIdentifiers = assignedIdentifiersTable.get(node); - HashSet<Node> foundVariables = new HashSet<Node>(foundIdentifiers); + HashSet<Node> foundVariables = new HashSet<>(foundIdentifiers); foundVariables.removeAll(expectedOutputParametersTable.get(node)); - expectedOutputParametersTable.put(node.getThen(), - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(node.getThen(), expectedOutputParametersTable.get(node)); expectedVariablesTable.put(node.getThen(), foundVariables); node.getThen().apply(this); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getElsifSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getElsifSubstitutions()); for (PSubstitution e : copy) { - expectedOutputParametersTable.put(e, - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(e, expectedOutputParametersTable.get(node)); expectedVariablesTable.put(e, foundVariables); e.apply(this); } if (node.getElse() != null) { - expectedOutputParametersTable.put(node.getElse(), - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(node.getElse(), expectedOutputParametersTable.get(node)); expectedVariablesTable.put(node.getElse(), foundVariables); node.getElse().apply(this); } else { - unchangedVariablesNull.put(node, - assignedIdentifiersTable.get(node.getThen())); + unchangedVariablesNull.put(node, assignedIdentifiersTable.get(node.getThen())); } } @Override public void caseAIfElsifSubstitution(AIfElsifSubstitution node) { - expectedOutputParametersTable.put(node.getThenSubstitution(), - expectedOutputParametersTable.get(node)); - expectedVariablesTable.put(node.getThenSubstitution(), - expectedVariablesTable.get(node)); + expectedOutputParametersTable.put(node.getThenSubstitution(), expectedOutputParametersTable.get(node)); + expectedVariablesTable.put(node.getThenSubstitution(), expectedVariablesTable.get(node)); node.getThenSubstitution().apply(this); } @@ -273,28 +249,22 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { // HashSet<Node> foundVariables = new HashSet<Node>(foundIdentifiers); // foundVariables.removeAll(expectedOutputParametersTable.get(node)); - expectedOutputParametersTable.put(node.getSubstitution(), - expectedOutputParametersTable.get(node)); - expectedVariablesTable.put(node.getSubstitution(), - expectedVariablesTable.get(node)); + expectedOutputParametersTable.put(node.getSubstitution(), expectedOutputParametersTable.get(node)); + expectedVariablesTable.put(node.getSubstitution(), expectedVariablesTable.get(node)); node.getSubstitution().apply(this); } @Override public void caseAAssertionSubstitution(AAssertionSubstitution node) { - expectedOutputParametersTable.put(node.getSubstitution(), - expectedOutputParametersTable.get(node)); - expectedVariablesTable.put(node.getSubstitution(), - expectedVariablesTable.get(node)); + expectedOutputParametersTable.put(node.getSubstitution(), expectedOutputParametersTable.get(node)); + expectedVariablesTable.put(node.getSubstitution(), expectedVariablesTable.get(node)); node.getSubstitution().apply(this); } @Override public void caseABlockSubstitution(ABlockSubstitution node) { - expectedOutputParametersTable.put(node.getSubstitution(), - expectedOutputParametersTable.get(node)); - expectedVariablesTable.put(node.getSubstitution(), - expectedVariablesTable.get(node)); + expectedOutputParametersTable.put(node.getSubstitution(), expectedOutputParametersTable.get(node)); + expectedVariablesTable.put(node.getSubstitution(), expectedVariablesTable.get(node)); node.getSubstitution().apply(this); } @@ -303,27 +273,24 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { check(node); // Separating variables and output parameters HashSet<Node> foundIdentifiers = assignedIdentifiersTable.get(node); - HashSet<Node> variables = new HashSet<Node>(foundIdentifiers); + HashSet<Node> variables = new HashSet<>(foundIdentifiers); variables.removeAll(expectedOutputParametersTable.get(node)); - expectedOutputParametersTable.put(node.getThen(), - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(node.getThen(), expectedOutputParametersTable.get(node)); expectedVariablesTable.put(node.getThen(), variables); node.getThen().apply(this); { - List<PSubstitution> copy = new ArrayList<PSubstitution>( + List<PSubstitution> copy = new ArrayList<>( node.getWhenSubstitutions()); for (PSubstitution e : copy) { - expectedOutputParametersTable.put(e, - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(e, expectedOutputParametersTable.get(node)); expectedVariablesTable.put(e, variables); e.apply(this); } } if (node.getElse() != null) { - expectedOutputParametersTable.put(node.getElse(), - expectedOutputParametersTable.get(node)); + expectedOutputParametersTable.put(node.getElse(), expectedOutputParametersTable.get(node)); expectedVariablesTable.put(node.getElse(), variables); node.getElse().apply(this); } @@ -332,10 +299,8 @@ public class UnchangedVariablesFinder extends DepthFirstAdapter { @Override public void caseASelectWhenSubstitution(ASelectWhenSubstitution node) { check(node); - expectedOutputParametersTable.put(node.getSubstitution(), - expectedOutputParametersTable.get(node)); - expectedVariablesTable.put(node.getSubstitution(), - expectedVariablesTable.get(node)); + expectedOutputParametersTable.put(node.getSubstitution(), expectedOutputParametersTable.get(node)); + expectedVariablesTable.put(node.getSubstitution(), expectedVariablesTable.get(node)); node.getSubstitution().apply(this); } diff --git a/src/main/java/de/tlc4b/btypes/AbstractHasFollowers.java b/src/main/java/de/tlc4b/btypes/AbstractHasFollowers.java index f13dc8c8869251ddf92c85a6bb91469317f9e5fd..3e034c4f1671d5f0422551ba0b7ea68fc3acb300 100644 --- a/src/main/java/de/tlc4b/btypes/AbstractHasFollowers.java +++ b/src/main/java/de/tlc4b/btypes/AbstractHasFollowers.java @@ -8,7 +8,7 @@ public abstract class AbstractHasFollowers implements BType { public abstract boolean contains(BType other); - private ArrayList<Object> followers = new ArrayList<Object>(); + private final ArrayList<Object> followers = new ArrayList<>(); public ArrayList<Object> getFollowers() { return this.followers; @@ -20,7 +20,7 @@ public abstract class AbstractHasFollowers implements BType { } public String printFollower() { - StringBuffer res = new StringBuffer(); + StringBuilder res = new StringBuilder(); res.append("["); for (Object o : followers) { if (!(o instanceof Node)) { @@ -41,7 +41,7 @@ public abstract class AbstractHasFollowers implements BType { if (this == newType) { return; } - ArrayList<Object> list = new ArrayList<Object>(followers); + ArrayList<Object> list = new ArrayList<>(followers); for (Object obj : list) { if (obj instanceof Node) { typechecker.setType((Node) obj, newType); diff --git a/src/main/java/de/tlc4b/btypes/BType.java b/src/main/java/de/tlc4b/btypes/BType.java index 552e540fc4af31c017221530228b90240c834c14..f70e953d5b42bbf82c361d190b5f93a0fa83c786 100644 --- a/src/main/java/de/tlc4b/btypes/BType.java +++ b/src/main/java/de/tlc4b/btypes/BType.java @@ -4,9 +4,9 @@ import de.be4.classicalb.core.parser.node.PExpression; import de.tlc4b.analysis.Typechecker; public interface BType { - public BType unify(BType other, ITypechecker typechecker); - public boolean isUntyped(); - public boolean compare(BType other); - public boolean containsInfiniteType(); - public PExpression createASTNode(Typechecker typechecker); + BType unify(BType other, ITypechecker typechecker); + boolean isUntyped(); + boolean compare(BType other); + boolean containsInfiniteType(); + PExpression createASTNode(Typechecker typechecker); } diff --git a/src/main/java/de/tlc4b/btypes/BoolType.java b/src/main/java/de/tlc4b/btypes/BoolType.java index 5d06ed9adfab70f8c039f8d2436218986c9cdc7b..354f185f62228695e056b5af6e247dc7dd19e09b 100644 --- a/src/main/java/de/tlc4b/btypes/BoolType.java +++ b/src/main/java/de/tlc4b/btypes/BoolType.java @@ -7,7 +7,7 @@ import de.tlc4b.exceptions.UnificationException; public class BoolType implements BType { - private static BoolType instance = new BoolType(); + private static final BoolType instance = new BoolType(); public static BoolType getInstance() { return instance; @@ -37,10 +37,7 @@ public class BoolType implements BType { } public boolean compare(BType other) { - if (other instanceof UntypedType || other instanceof BoolType) - return true; - else - return false; + return other instanceof UntypedType || other instanceof BoolType; } public boolean containsInfiniteType() { diff --git a/src/main/java/de/tlc4b/btypes/EnumeratedSetElement.java b/src/main/java/de/tlc4b/btypes/EnumeratedSetElement.java index dd3d0dd55208d516f197c4c9b4d3ec45553b1889..e20b807696b7448adcd7d8c3fbb0e87f592cdbec 100644 --- a/src/main/java/de/tlc4b/btypes/EnumeratedSetElement.java +++ b/src/main/java/de/tlc4b/btypes/EnumeratedSetElement.java @@ -1,15 +1,13 @@ package de.tlc4b.btypes; -import java.util.ArrayList; - import de.be4.classicalb.core.parser.node.AIdentifierExpression; import de.be4.classicalb.core.parser.node.PExpression; -import de.be4.classicalb.core.parser.node.TIdentifierLiteral; import de.tlc4b.analysis.Typechecker; import de.tlc4b.exceptions.UnificationException; +import de.tlc4b.util.UtilMethods; public class EnumeratedSetElement implements BType { - private String name; + private final String name; public EnumeratedSetElement(String name) { this.name = name; @@ -50,9 +48,7 @@ public class EnumeratedSetElement implements BType { if (other instanceof UntypedType) return true; if (other instanceof EnumeratedSetElement) { - if (((EnumeratedSetElement) other).getName().equals(this.name)) { - return true; - } + return ((EnumeratedSetElement) other).getName().equals(this.name); } return false; } @@ -62,10 +58,7 @@ public class EnumeratedSetElement implements BType { } public PExpression createASTNode(Typechecker typechecker) { - TIdentifierLiteral literal = new TIdentifierLiteral(name); - ArrayList<TIdentifierLiteral> idList = new ArrayList<TIdentifierLiteral>(); - idList.add(literal); - AIdentifierExpression id = new AIdentifierExpression(idList); + AIdentifierExpression id = UtilMethods.createAIdentifierExpression(name); typechecker.setType(id, new SetType(this)); return id; } diff --git a/src/main/java/de/tlc4b/btypes/FunctionType.java b/src/main/java/de/tlc4b/btypes/FunctionType.java index c38fe6f57989e0b592bbd27fbd2867b8afcf5b57..f6aa14c7fb6011109e19b34a488c76a3dea624c9 100644 --- a/src/main/java/de/tlc4b/btypes/FunctionType.java +++ b/src/main/java/de/tlc4b/btypes/FunctionType.java @@ -70,8 +70,7 @@ public class FunctionType extends AbstractHasFollowers { @Override public String toString() { - String res = "FUNC(" + domain + "," + range + ")"; - return res; + return "FUNC(" + domain + "," + range + ")"; } public void update(BType oldType, BType newType) { @@ -96,10 +95,7 @@ public class FunctionType extends AbstractHasFollowers { if (t instanceof PairType) { return ((PairType) t).getFirst().compare(domain) && ((PairType) t).getSecond().compare(range); - } else if (t instanceof UntypedType) { - return true; - } else - return false; + } else return t instanceof UntypedType; } return false; } @@ -114,8 +110,7 @@ public class FunctionType extends AbstractHasFollowers { return true; } if (range instanceof AbstractHasFollowers) { - if (((AbstractHasFollowers) range).contains(other)) - return true; + return ((AbstractHasFollowers) range).contains(other); } return false; } diff --git a/src/main/java/de/tlc4b/btypes/ITypechecker.java b/src/main/java/de/tlc4b/btypes/ITypechecker.java index 9e996d9a0756620a6fe257350ad5d4c6c99fb443..52e63a208b7278f123127590c62583f0f0f3f284 100644 --- a/src/main/java/de/tlc4b/btypes/ITypechecker.java +++ b/src/main/java/de/tlc4b/btypes/ITypechecker.java @@ -4,6 +4,6 @@ import de.be4.classicalb.core.parser.node.Node; public interface ITypechecker { - public void setType(Node node, BType type); - public void updateType(Node node, AbstractHasFollowers oldType, BType newType); + void setType(Node node, BType type); + void updateType(Node node, AbstractHasFollowers oldType, BType newType); } diff --git a/src/main/java/de/tlc4b/btypes/IntegerOrSetOfPairType.java b/src/main/java/de/tlc4b/btypes/IntegerOrSetOfPairType.java index a9215a24e57a00e5c935f824c7cf660a6b11511b..fcf2cc7c8fe316cd418b1558b55e1970a6fb8679 100644 --- a/src/main/java/de/tlc4b/btypes/IntegerOrSetOfPairType.java +++ b/src/main/java/de/tlc4b/btypes/IntegerOrSetOfPairType.java @@ -22,12 +22,10 @@ public class IntegerOrSetOfPairType extends AbstractHasFollowers { public IntegerOrSetOfPairType(SourcePosition sourcePosition, SourcePosition sourcePosition2) { - IntegerOrSetType i1 = new IntegerOrSetType(); - this.first = i1; + this.first = new IntegerOrSetType(); first.addFollower(this); - IntegerOrSetType i2 = new IntegerOrSetType(); - this.second = i2; + this.second = new IntegerOrSetType(); second.addFollower(this); } @@ -55,7 +53,6 @@ public class IntegerOrSetOfPairType extends AbstractHasFollowers { } this.setFollowersTo(IntegerType.getInstance(), typechecker); - return; } else if (newType instanceof SetType) { SetType newFirst; SetType newSecond; @@ -96,7 +93,6 @@ public class IntegerOrSetOfPairType extends AbstractHasFollowers { newFirst.getSubtype(), newSecond.getSubtype())); setOfPairSetType.unify(this, typechecker); } - return; } else if (newType instanceof IntegerOrSetOfPairType) { if (this.first == oldType) { first.deleteFollower(this); @@ -199,10 +195,7 @@ public class IntegerOrSetOfPairType extends AbstractHasFollowers { return true; else if (other instanceof SetType) { BType subType = ((SetType) other).getSubtype(); - if (subType instanceof UntypedType || subType instanceof PairType) - return true; - else - return false; + return subType instanceof UntypedType || subType instanceof PairType; } else return false; } @@ -212,11 +205,8 @@ public class IntegerOrSetOfPairType extends AbstractHasFollowers { if (this.first.equals(other) || this.second.equals(other)) { return true; } - - if(first.contains(other) || second.contains(other)){ - return true; - }else - return false; + + return first.contains(other) || second.contains(other); } public boolean containsInfiniteType() { diff --git a/src/main/java/de/tlc4b/btypes/IntegerType.java b/src/main/java/de/tlc4b/btypes/IntegerType.java index 3143b42d6747e5914f33d0f4cfd98f29b5d393cf..377773d9634ed244c37182332061c27c722433a4 100644 --- a/src/main/java/de/tlc4b/btypes/IntegerType.java +++ b/src/main/java/de/tlc4b/btypes/IntegerType.java @@ -7,7 +7,7 @@ import de.tlc4b.exceptions.UnificationException; public class IntegerType implements BType { - private static IntegerType instance = new IntegerType(); + private static final IntegerType instance = new IntegerType(); public static IntegerType getInstance() { return instance; @@ -47,10 +47,8 @@ public class IntegerType implements BType { public boolean compare(BType other) { if (other instanceof UntypedType || other instanceof IntegerType) return true; - if (other instanceof IntegerOrSetType - || other instanceof IntegerOrSetOfPairType) - return true; - return false; + return other instanceof IntegerOrSetType + || other instanceof IntegerOrSetOfPairType; } public boolean containsInfiniteType() { diff --git a/src/main/java/de/tlc4b/btypes/PairType.java b/src/main/java/de/tlc4b/btypes/PairType.java index e5c2ff7aa8b3b85bb08ad0eb2c3960cabd6fa154..0cac6113d4598d1820c6121bfb091e825d32eaee 100644 --- a/src/main/java/de/tlc4b/btypes/PairType.java +++ b/src/main/java/de/tlc4b/btypes/PairType.java @@ -64,10 +64,9 @@ public class PairType extends AbstractHasFollowers { @Override public String toString() { String res = ""; - if(this.equals(first)|| this.equals(second)){ + if (this.equals(first)|| this.equals(second)) { res += "(Recursive Type)"; - return res; - }else{ + } else { if (first instanceof PairType) { res += "(" + first + ")"; } else @@ -77,18 +76,12 @@ public class PairType extends AbstractHasFollowers { res += "(" + second + ")"; } else res += second; - return res; } - - - + return res; } public boolean isUntyped() { - if (first.isUntyped() || second.isUntyped()) - return true; - else - return false; + return first.isUntyped() || second.isUntyped(); } public boolean compare(BType other) { @@ -114,8 +107,7 @@ public class PairType extends AbstractHasFollowers { return true; } if (second instanceof AbstractHasFollowers) { - if (((AbstractHasFollowers) second).contains(other)) - return true; + return ((AbstractHasFollowers) second).contains(other); } return false; } diff --git a/src/main/java/de/tlc4b/btypes/StringType.java b/src/main/java/de/tlc4b/btypes/StringType.java index f37ac4ec5eaa1a5a482eecf7afd22a9db00bffc5..2ca76abdd1dc43f2bcf668d6b2e5e34b15fcf8ae 100644 --- a/src/main/java/de/tlc4b/btypes/StringType.java +++ b/src/main/java/de/tlc4b/btypes/StringType.java @@ -7,7 +7,7 @@ import de.tlc4b.exceptions.UnificationException; public class StringType implements BType { - private static StringType instance = new StringType(); + private static final StringType instance = new StringType(); public static StringType getInstance() { return instance; @@ -42,10 +42,7 @@ public class StringType implements BType { if (other instanceof UntypedType) { return true; } - if (other instanceof StringType) { - return true; - } - return false; + return other instanceof StringType; } public boolean containsInfiniteType() { diff --git a/src/main/java/de/tlc4b/btypes/StructType.java b/src/main/java/de/tlc4b/btypes/StructType.java index 4893a3e99abd567d805f1f7ccc5ce3ac394d83e4..38c232b399a76b4466efb3decb4deec5f16882cc 100644 --- a/src/main/java/de/tlc4b/btypes/StructType.java +++ b/src/main/java/de/tlc4b/btypes/StructType.java @@ -7,7 +7,6 @@ import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Set; -import de.be4.classicalb.core.parser.node.AIdentifierExpression; import de.be4.classicalb.core.parser.node.ARecEntry; import de.be4.classicalb.core.parser.node.AStructExpression; import de.be4.classicalb.core.parser.node.PExpression; @@ -18,11 +17,11 @@ import de.tlc4b.exceptions.UnificationException; public class StructType extends AbstractHasFollowers { - private LinkedHashMap<String, BType> types; + private final LinkedHashMap<String, BType> types; private boolean complete; public StructType() { - types = new LinkedHashMap<String, BType>(); + types = new LinkedHashMap<>(); } public BType getType(String fieldName) { @@ -42,7 +41,7 @@ public class StructType extends AbstractHasFollowers { @Override public String toString() { - StringBuffer res = new StringBuffer(); + StringBuilder res = new StringBuilder(); res.append("struct("); Iterator<Entry<String, BType>> iterator = types.entrySet().iterator(); @@ -50,7 +49,7 @@ public class StructType extends AbstractHasFollowers { res.append("..."); while (iterator.hasNext()) { Entry<String, BType> next = iterator.next(); - String fieldName = (String) next.getKey(); + String fieldName = next.getKey(); res.append(fieldName).append(":").append(next.getValue()); if (iterator.hasNext()) res.append(","); @@ -60,10 +59,7 @@ public class StructType extends AbstractHasFollowers { } public void update(BType oldType, BType newType) { - Iterator<Entry<String, BType>> iterator = this.types.entrySet() - .iterator(); - while (iterator.hasNext()) { - Entry<String, BType> next = iterator.next(); + for (Entry<String, BType> next : this.types.entrySet()) { String name = next.getKey(); BType type = next.getValue(); if (type == oldType) { @@ -87,17 +83,13 @@ public class StructType extends AbstractHasFollowers { if (other instanceof StructType) { StructType s = (StructType) other; - Iterator<Entry<String, BType>> iterator = s.types.entrySet() - .iterator(); - while (iterator.hasNext()) { - Entry<String, BType> next = iterator.next(); + for (Entry<String, BType> next : s.types.entrySet()) { String fieldName = next.getKey(); BType sType = next.getValue(); if (this.types.containsKey(fieldName)) { - BType res = this.types.get(fieldName).unify(sType, - typechecker); + BType res = this.types.get(fieldName).unify(sType, typechecker); this.types.put(fieldName, res); - if(res instanceof AbstractHasFollowers){ + if (res instanceof AbstractHasFollowers) { ((AbstractHasFollowers) res).addFollower(this); } } else { @@ -118,9 +110,8 @@ public class StructType extends AbstractHasFollowers { } public boolean isUntyped() { - Iterator<BType> iterator = types.values().iterator(); - while (iterator.hasNext()) { - if (iterator.next().isUntyped()) { + for (BType bType : types.values()) { + if (bType.isUntyped()) { return true; } } @@ -134,15 +125,15 @@ public class StructType extends AbstractHasFollowers { if (other instanceof StructType) { StructType s = (StructType) other; Iterator<String> itr = types.keySet().iterator(); - Set<String> intersection = new HashSet<String>(); + Set<String> intersection = new HashSet<>(); while (itr.hasNext()) { String temp = itr.next(); - if (s.types.keySet().contains(temp)) { + if (s.types.containsKey(temp)) { intersection.add(temp); } } if (this.complete) { - Set<String> temp = new HashSet<String>(s.types.keySet()); + Set<String> temp = new HashSet<>(s.types.keySet()); temp.removeAll(intersection); if (!temp.equals(new HashSet<String>())) { return false; @@ -150,16 +141,13 @@ public class StructType extends AbstractHasFollowers { } if (s.complete) { - Set<String> temp = new HashSet<String>(this.types.keySet()); + Set<String> temp = new HashSet<>(this.types.keySet()); temp.removeAll(intersection); if (!temp.equals(new HashSet<String>())) { return false; } } - Iterator<Entry<String, BType>> iterator = types.entrySet() - .iterator(); - while (iterator.hasNext()) { - Entry<String, BType> next = iterator.next(); + for (Entry<String, BType> next : types.entrySet()) { String name = next.getKey(); BType value = next.getValue(); if (!this.types.get(name).compare(value)) { @@ -173,9 +161,7 @@ public class StructType extends AbstractHasFollowers { @Override public boolean contains(BType other) { - Iterator<BType> itr = types.values().iterator(); - while (itr.hasNext()) { - BType t = itr.next(); + for (BType t : types.values()) { if (t.equals(other)) { return true; } @@ -189,27 +175,21 @@ public class StructType extends AbstractHasFollowers { } public boolean containsInfiniteType() { - Iterator<BType> iterator = this.types.values().iterator(); - while (iterator.hasNext()) { - if (iterator.next().containsInfiniteType()) + for (BType bType : this.types.values()) { + if (bType.containsInfiniteType()) return true; } return false; } public PExpression createASTNode(Typechecker typechecker) { - ArrayList<PRecEntry> list = new ArrayList<PRecEntry>(); + ArrayList<PRecEntry> list = new ArrayList<>(); Set<Entry<String, BType>> entrySet = this.types.entrySet(); for (Entry<String, BType> entry : entrySet) { String name = entry.getKey(); BType type = entry.getValue(); - TIdentifierLiteral literal = new TIdentifierLiteral(name); - ArrayList<TIdentifierLiteral> idList = new ArrayList<TIdentifierLiteral>(); - idList.add(literal); - AIdentifierExpression id = new AIdentifierExpression(idList); - ARecEntry recEntry = new ARecEntry(id, - type.createASTNode(typechecker)); + ARecEntry recEntry = new ARecEntry(new TIdentifierLiteral(name), type.createASTNode(typechecker)); list.add(recEntry); } AStructExpression node = new AStructExpression(list); diff --git a/src/main/java/de/tlc4b/exceptions/LTLParseException.java b/src/main/java/de/tlc4b/exceptions/LTLParseException.java index c7cc54a84ed713a7c4e7bb2dfe7e1e4a02ca0675..cb5cd268d4c3684ca22cde75d31d2e1c5c90e12c 100644 --- a/src/main/java/de/tlc4b/exceptions/LTLParseException.java +++ b/src/main/java/de/tlc4b/exceptions/LTLParseException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class LTLParseException extends TLC4BException{ +public class LTLParseException extends TLC4BException { + public LTLParseException(String message) { + super(message); + } + + public LTLParseException(String message, Throwable cause) { + super(message, cause); + } - public LTLParseException(String e) { - super(e); + public LTLParseException(Throwable cause) { + super(cause); } @Override public String getError() { return "LTLParseError"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/NotSupportedException.java b/src/main/java/de/tlc4b/exceptions/NotSupportedException.java index 476c3556229951f09ac90ad3d80aba2efa4a9df9..b86956383da8da8ce69a321031628edfb09f5f0c 100644 --- a/src/main/java/de/tlc4b/exceptions/NotSupportedException.java +++ b/src/main/java/de/tlc4b/exceptions/NotSupportedException.java @@ -1,11 +1,16 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class NotSupportedException extends TLC4BException{ +public class NotSupportedException extends TLC4BException { + public NotSupportedException(String message) { + super(message); + } + + public NotSupportedException(String message, Throwable cause) { + super(message, cause); + } - - public NotSupportedException(String e){ - super(e); + public NotSupportedException(Throwable cause) { + super(cause); } @Override diff --git a/src/main/java/de/tlc4b/exceptions/NotSupportedLTLFormulaException.java b/src/main/java/de/tlc4b/exceptions/NotSupportedLTLFormulaException.java index 8d36dac7f695c6e53cb074f427f6100ca81c650b..c2d93b6cc32f80a964efe6b1e5091e2aa134c1d0 100644 --- a/src/main/java/de/tlc4b/exceptions/NotSupportedLTLFormulaException.java +++ b/src/main/java/de/tlc4b/exceptions/NotSupportedLTLFormulaException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class NotSupportedLTLFormulaException extends TLC4BException{ +public class NotSupportedLTLFormulaException extends TLC4BException { + public NotSupportedLTLFormulaException(String message) { + super(message); + } + + public NotSupportedLTLFormulaException(String message, Throwable cause) { + super(message, cause); + } - public NotSupportedLTLFormulaException(String e) { - super(e); + public NotSupportedLTLFormulaException(Throwable cause) { + super(cause); } @Override public String getError() { return "NotSupportedLTLFormula"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/ScopeException.java b/src/main/java/de/tlc4b/exceptions/ScopeException.java index c6acf285131f93271bbe6787304faddb40b670d1..7c13b8cd8518de3b1c1cd4d444ec6ff544700b7a 100644 --- a/src/main/java/de/tlc4b/exceptions/ScopeException.java +++ b/src/main/java/de/tlc4b/exceptions/ScopeException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class ScopeException extends TLC4BException{ +public class ScopeException extends TLC4BException { + public ScopeException(String message) { + super(message); + } + + public ScopeException(String message, Throwable cause) { + super(message, cause); + } - public ScopeException(String e){ - super(e); + public ScopeException(Throwable cause) { + super(cause); } @Override public String getError() { return "ScopeException"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/SubstitutionException.java b/src/main/java/de/tlc4b/exceptions/SubstitutionException.java index fd8b81fb00372e7a2250fdd4a8c9678247bc9860..ba32275ffd39b64f5f1a82d134d81f4aeec78115 100644 --- a/src/main/java/de/tlc4b/exceptions/SubstitutionException.java +++ b/src/main/java/de/tlc4b/exceptions/SubstitutionException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class SubstitutionException extends TLC4BException{ +public class SubstitutionException extends TLC4BException { + public SubstitutionException(String message) { + super(message); + } + + public SubstitutionException(String message, Throwable cause) { + super(message, cause); + } - public SubstitutionException(String e) { - super(e); + public SubstitutionException(Throwable cause) { + super(cause); } @Override public String getError() { return "SubstitutionError"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/TLC4BException.java b/src/main/java/de/tlc4b/exceptions/TLC4BException.java index f9e14ea9b66948ccb78399fce3e494d5fd42b7df..01f6656ba879853a6d3ddf1a985c6b29a1804282 100644 --- a/src/main/java/de/tlc4b/exceptions/TLC4BException.java +++ b/src/main/java/de/tlc4b/exceptions/TLC4BException.java @@ -1,12 +1,17 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") public abstract class TLC4BException extends RuntimeException { + protected TLC4BException(String message) { + super(message); + } + + protected TLC4BException(String message, Throwable cause) { + super(message, cause); + } - public TLC4BException(String e) { - super(e); + protected TLC4BException(Throwable cause) { + super(cause); } public abstract String getError(); - } diff --git a/src/main/java/de/tlc4b/exceptions/TLC4BIOException.java b/src/main/java/de/tlc4b/exceptions/TLC4BIOException.java index 9d5f308b44b1416a866ab812a24ca91a724fab53..51e226d2cf730a8e4af4d2a7bfdc395ceca8968a 100644 --- a/src/main/java/de/tlc4b/exceptions/TLC4BIOException.java +++ b/src/main/java/de/tlc4b/exceptions/TLC4BIOException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class TLC4BIOException extends TLC4BException{ +public class TLC4BIOException extends TLC4BException { + public TLC4BIOException(String message) { + super(message); + } + + public TLC4BIOException(String message, Throwable cause) { + super(message, cause); + } - public TLC4BIOException(String e) { - super(e); + public TLC4BIOException(Throwable cause) { + super(cause); } @Override public String getError() { return "I/O Error"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/TranslationException.java b/src/main/java/de/tlc4b/exceptions/TranslationException.java index fa71eccb25ba427f582ea82b6b6b293122ea3b85..7ac9a45562b27b6efa222ebd13b5e604bd46916c 100644 --- a/src/main/java/de/tlc4b/exceptions/TranslationException.java +++ b/src/main/java/de/tlc4b/exceptions/TranslationException.java @@ -1,15 +1,20 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class TranslationException extends TLC4BException{ +public class TranslationException extends TLC4BException { + public TranslationException(String message) { + super(message); + } + + public TranslationException(String message, Throwable cause) { + super(message, cause); + } - public TranslationException(String e) { - super(e); + public TranslationException(Throwable cause) { + super(cause); } @Override public String getError() { return "TranslationError"; } - } diff --git a/src/main/java/de/tlc4b/exceptions/TypeErrorException.java b/src/main/java/de/tlc4b/exceptions/TypeErrorException.java index c0f72dd0eb9e5f64bb7536d7c7ad202e998cd92e..5b34d49497eb1b3358c6bdf7c583b33ed0795ca7 100644 --- a/src/main/java/de/tlc4b/exceptions/TypeErrorException.java +++ b/src/main/java/de/tlc4b/exceptions/TypeErrorException.java @@ -1,10 +1,16 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") public class TypeErrorException extends TLC4BException { + public TypeErrorException(String message) { + super(message); + } + + public TypeErrorException(String message, Throwable cause) { + super(message, cause); + } - public TypeErrorException(String e) { - super(e); + public TypeErrorException(Throwable cause) { + super(cause); } @Override diff --git a/src/main/java/de/tlc4b/exceptions/UnificationException.java b/src/main/java/de/tlc4b/exceptions/UnificationException.java index 4e0d579af2d6189f5cc0bdb0c1ac1139aa0fe3ee..3a4f375f1377b9a37a80348e2d51a401b1c4f760 100644 --- a/src/main/java/de/tlc4b/exceptions/UnificationException.java +++ b/src/main/java/de/tlc4b/exceptions/UnificationException.java @@ -1,7 +1,6 @@ package de.tlc4b.exceptions; -@SuppressWarnings("serial") -public class UnificationException extends RuntimeException{ +public class UnificationException extends RuntimeException { public UnificationException() { super(""); diff --git a/src/main/java/de/tlc4b/ltl/LTLFormulaPrinter.java b/src/main/java/de/tlc4b/ltl/LTLFormulaPrinter.java index 012e21779354845c12c7b2d4052433afd2af138f..bbc4bd5c3990fbbd2e3553d505ed12ec6990613a 100644 --- a/src/main/java/de/tlc4b/ltl/LTLFormulaPrinter.java +++ b/src/main/java/de/tlc4b/ltl/LTLFormulaPrinter.java @@ -186,7 +186,7 @@ public class LTLFormulaPrinter extends DepthFirstAdapter { @Override public void caseADetLtl(ADetLtl node) { - List<PActions> copy = new ArrayList<PActions>(node.getArgs()); + List<PActions> copy = new ArrayList<>(node.getArgs()); LinkedHashMap<String, Node> operations = ltlFormulaVisitor .getMachineContext().getOperations(); if (copy.size() > 1) { @@ -222,7 +222,7 @@ public class LTLFormulaPrinter extends DepthFirstAdapter { tlaPrinter.moduleStringAppend("(ENABLED("); tlaPrinter.printOperationCall(op1); tlaPrinter.moduleStringAppend(") => \\neg("); - ArrayList<Node> remainingOperations = new ArrayList<Node>(operations.values()); + ArrayList<Node> remainingOperations = new ArrayList<>(operations.values()); remainingOperations.remove(op1); for (int i = 0; i < remainingOperations.size(); i++) { if (i != 0) { diff --git a/src/main/java/de/tlc4b/ltl/LTLFormulaVisitor.java b/src/main/java/de/tlc4b/ltl/LTLFormulaVisitor.java index 56108205d108030724fdf4a2627ea2fe2f43913e..6d5b889205fe7ad0751a26100384cb74b145c3aa 100644 --- a/src/main/java/de/tlc4b/ltl/LTLFormulaVisitor.java +++ b/src/main/java/de/tlc4b/ltl/LTLFormulaVisitor.java @@ -57,15 +57,15 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { private final ArrayList<LTLBPredicate> bPredicates; private final Hashtable<String, AIdentifierExpression> ltlIdentifierTable; - private ArrayList<Hashtable<String, AIdentifierExpression>> contextTable; + private final ArrayList<Hashtable<String, AIdentifierExpression>> contextTable; public LTLFormulaVisitor(String name, MachineContext machineContext) { this.name = name; this.machineContext = machineContext; - this.bPredicates = new ArrayList<LTLBPredicate>(); - this.ltlNodeToBNodeTable = new LinkedHashMap<de.be4.ltl.core.parser.node.Node, de.be4.classicalb.core.parser.node.Node>(); - this.ltlIdentifierTable = new Hashtable<String, AIdentifierExpression>(); - this.contextTable = new ArrayList<Hashtable<String, AIdentifierExpression>>(); + this.bPredicates = new ArrayList<>(); + this.ltlNodeToBNodeTable = new LinkedHashMap<>(); + this.ltlIdentifierTable = new Hashtable<>(); + this.contextTable = new ArrayList<>(); } public void parseDefinition(AExpressionDefinitionDefinition def) { @@ -78,7 +78,7 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { this.ltlFormulaStart = parseLTLFormula(ltlFormula); } catch (Exception e) { String message = "Parsing definition " + name + " (line " + def.getStartPos().getLine() + "):\n"; - throw new LTLParseException(message + e.getMessage()); + throw new LTLParseException(message + e.getMessage(), e); } } @@ -86,7 +86,7 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { try { this.ltlFormulaStart = parseLTLFormula(ltlString); } catch (Exception e) { - throw new LTLParseException(e.getMessage()); + throw new LTLParseException(e); } } @@ -132,7 +132,7 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { PushbackReader r = new PushbackReader(reader); Lexer l = new LtlLexer(r); Parser p = new Parser(l); - Start ast = null; + Start ast; ast = p.parse(); return ast; } @@ -150,13 +150,12 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { } private de.be4.classicalb.core.parser.node.Start parseBPredicate(String text) { - String bPredicate = "#PREDICATE " + text; BParser parser = new BParser("Testing"); - de.be4.classicalb.core.parser.node.Start start = null; + de.be4.classicalb.core.parser.node.Start start; try { - start = parser.parse(bPredicate, false); + start = parser.parsePredicate(text); } catch (BCompoundException e) { - throw new LTLParseException(e.getMessage()); + throw new LTLParseException(e); } return start; @@ -177,12 +176,12 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { String bPredicateString, PLtl ltl) { // create an identifier (b ast node) for the parameter of the // quantification - List<TIdentifierLiteral> list = new ArrayList<TIdentifierLiteral>(); + List<TIdentifierLiteral> list = new ArrayList<>(); list.add(new TIdentifierLiteral(parameterName)); AIdentifierExpression parameterNode = new AIdentifierExpression(list); // add the created identifier to the current context - Hashtable<String, AIdentifierExpression> currentContext = new Hashtable<String, AIdentifierExpression>(); + Hashtable<String, AIdentifierExpression> currentContext = new Hashtable<>(); currentContext.put(parameterName, parameterNode); this.contextTable.add(currentContext); @@ -208,9 +207,9 @@ public class LTLFormulaVisitor extends DepthFirstAdapter { } private LinkedHashMap<String, Node> getUnifiedContext() { - LinkedHashMap<String, Node> context = new LinkedHashMap<String, Node>(); - for (int i = 0; i < contextTable.size(); i++) { - context.putAll(contextTable.get(i)); + LinkedHashMap<String, Node> context = new LinkedHashMap<>(); + for (Hashtable<String, AIdentifierExpression> stringAIdentifierExpressionHashtable : contextTable) { + context.putAll(stringAIdentifierExpressionHashtable); } return context; } diff --git a/src/main/java/de/tlc4b/prettyprint/TLAPrinter.java b/src/main/java/de/tlc4b/prettyprint/TLAPrinter.java index da66c6a45a33fe015c5b2472a173a8a549cfb71e..7c6f9510cece6e8bb051d46fa3600dbc4a4914ce 100644 --- a/src/main/java/de/tlc4b/prettyprint/TLAPrinter.java +++ b/src/main/java/de/tlc4b/prettyprint/TLAPrinter.java @@ -15,7 +15,7 @@ import de.tlc4b.analysis.MachineContext; import de.tlc4b.analysis.PrecedenceCollector; import de.tlc4b.analysis.PrimedNodesMarker; import de.tlc4b.analysis.Renamer; -import de.tlc4b.analysis.StandardMadules; +import de.tlc4b.analysis.StandardModules; import de.tlc4b.analysis.Typechecker; import de.tlc4b.analysis.UsedStandardModules; import de.tlc4b.analysis.typerestriction.TypeRestrictor; @@ -33,12 +33,12 @@ import de.tlc4b.tla.ConfigFile; import de.tlc4b.tla.TLADefinition; import de.tlc4b.tla.TLAModule; import de.tlc4b.tla.config.ConfigFileAssignment; -import static de.tlc4b.analysis.StandardMadules.*; +import static de.tlc4b.analysis.StandardModules.*; public class TLAPrinter extends DepthFirstAdapter { - private StringBuilder tlaModuleString; - private StringBuilder configFileString; + private final StringBuilder tlaModuleString; + private final StringBuilder configFileString; public StringBuilder getConfigString() { return configFileString; @@ -48,18 +48,16 @@ public class TLAPrinter extends DepthFirstAdapter { return tlaModuleString; } - private MachineContext machineContext; - private Typechecker typechecker; - private UnchangedVariablesFinder missingVariableFinder; - private PrecedenceCollector precedenceCollector; - private UsedStandardModules usedStandardModules; - private TypeRestrictor typeRestrictor; - private TLAModule tlaModule; - private ConfigFile configFile; - private PrimedNodesMarker primedNodesMarker; - private Renamer renamer; - private boolean recordLTLFormula = false; - private StringBuilder translatedLTLFormula = new StringBuilder(); + private final MachineContext machineContext; + private final Typechecker typechecker; + private final UnchangedVariablesFinder missingVariableFinder; + private final PrecedenceCollector precedenceCollector; + private final UsedStandardModules usedStandardModules; + private final TypeRestrictor typeRestrictor; + private final TLAModule tlaModule; + private final ConfigFile configFile; + private final PrimedNodesMarker primedNodesMarker; + private final Renamer renamer; private final InvariantPreservationAnalysis invariantPreservationAnalysis; public TLAPrinter(MachineContext machineContext, Typechecker typechecker, @@ -110,11 +108,11 @@ public class TLAPrinter extends DepthFirstAdapter { private void printSymmetry() { if (TLC4BGlobals.useSymmetry() - && machineContext.getDeferredSets().size() > 0) { + && !machineContext.getDeferredSets().isEmpty()) { moduleStringAppend("Symmetry == "); Collection<Node> values = machineContext.getDeferredSets().values(); - ArrayList<Node> array = new ArrayList<Node>(values); + ArrayList<Node> array = new ArrayList<>(values); for (int i = 0; i < array.size(); i++) { Node node = array.get(i); moduleStringAppend("Permutations("); @@ -147,7 +145,7 @@ public class TLAPrinter extends DepthFirstAdapter { public void printStrongFairness(String s) { moduleStringAppend(String - .format("([]<><<%s>>_vars \\/ <>[]~ENABLED(%s) \\/ []<> ENABLED(%s /\\ ", + .format("([]<><<%s>>_vars \\/ <>[]~ENABLED(%s) \\/ []<>ENABLED(%s /\\ ", s, s, s)); printVarsStuttering(); moduleStringAppend("))"); @@ -156,7 +154,7 @@ public class TLAPrinter extends DepthFirstAdapter { public void printWeakFairness(String s) { moduleStringAppend(String - .format("([]<><<%s>>_vars \\/ []<>~ENABLED(%s) \\/ []<> ENABLED(%s /\\ ", + .format("([]<><<%s>>_vars \\/ []<>~ENABLED(%s) \\/ []<>ENABLED(%s /\\ ", s, s, s)); printVarsStuttering(); moduleStringAppend("))"); @@ -168,9 +166,9 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend("([]<><<"); printOperationCall(operation); - moduleStringAppend(">>_vars \\/ []<>~ENABLED("); + moduleStringAppend(">>_vars \\/ []<>~ENABLED("); printOperationCall(operation); - moduleStringAppend(") \\/ []<> ENABLED("); + moduleStringAppend(") \\/ []<>ENABLED("); printOperationCall(operation); moduleStringAppend(" /\\ "); printVarsStuttering(); @@ -191,7 +189,7 @@ public class TLAPrinter extends DepthFirstAdapter { private void printVarsAsTuple() { ArrayList<Node> vars = this.tlaModule.getVariables(); - if (vars.size() == 0) + if (vars.isEmpty()) return; moduleStringAppend("<<"); for (int i = 0; i < vars.size(); i++) { @@ -205,16 +203,9 @@ public class TLAPrinter extends DepthFirstAdapter { private void printLTLFormulas() { ArrayList<LTLFormulaVisitor> visitors = machineContext.getLTLFormulas(); if (TLC4BGlobals.isCheckLTL()) { - for (int i = 0; i < visitors.size(); i++) { - LTLFormulaVisitor visitor = visitors.get(i); + for (LTLFormulaVisitor visitor : visitors) { moduleStringAppend(visitor.getName() + " == "); - if (TLC4BGlobals.getTestingMode() == true) { - recordLTLFormula = true; - visitor.printLTLFormula(this, typeRestrictor); - recordLTLFormula = false; - } else { - visitor.printLTLFormula(this, typeRestrictor); - } + visitor.printLTLFormula(this, typeRestrictor); moduleStringAppend("\n"); } } @@ -233,8 +224,7 @@ public class TLAPrinter extends DepthFirstAdapter { } if (TLC4BGlobals.isInvariant()) { for (int i = 0; i < configFile.getInvariantNumber(); i++) { - this.configFileString.append("INVARIANT Invariant" + (i + 1) - + "\n"); + this.configFileString.append("INVARIANT Invariant").append(i + 1).append("\n"); } } @@ -253,21 +243,20 @@ public class TLAPrinter extends DepthFirstAdapter { for (int i = 0; i < machineContext.getLTLFormulas().size(); i++) { LTLFormulaVisitor ltlVisitor = machineContext.getLTLFormulas() .get(i); - this.configFileString.append("PROPERTIES " - + ltlVisitor.getName() + "\n"); + this.configFileString.append("PROPERTIES ").append(ltlVisitor.getName()).append("\n"); } } // CONSTANTS ArrayList<ConfigFileAssignment> assignments = configFile .getAssignments(); - if (assignments.size() != 0) { + if (!assignments.isEmpty()) { configFileString.append("CONSTANTS\n"); - for (int i = 0; i < assignments.size(); i++) { - configFileString.append(assignments.get(i).getString(renamer)); + for (ConfigFileAssignment assignment : assignments) { + configFileString.append(assignment.getString(renamer)); } } if (TLC4BGlobals.useSymmetry() - && machineContext.getDeferredSets().size() > 0) { + && !machineContext.getDeferredSets().isEmpty()) { configFileString.append("SYMMETRY Symmetry\n"); } @@ -276,13 +265,11 @@ public class TLAPrinter extends DepthFirstAdapter { configFileString.append("Init_action = Init_action\n"); ArrayList<POperation> operations = tlaModule.getOperations(); - for (int i = 0; i < operations.size(); i++) { - AOperation node = (AOperation) operations.get(i); + for (POperation operation : operations) { + AOperation node = (AOperation) operation; String name = renamer.getNameOfRef(node); String actionName = name + "actions"; - configFileString.append(actionName).append(" = ") - .append(actionName); - configFileString.append("\n"); + configFileString.append(actionName).append(" = ").append(actionName).append("\n"); } configFileString.append("\n"); configFileString.append("VIEW myView"); @@ -292,9 +279,6 @@ public class TLAPrinter extends DepthFirstAdapter { public void moduleStringAppend(String str) { tlaModuleString.append(str); - if (recordLTLFormula) { - translatedLTLFormula.append(str); - } } private void printHeader() { @@ -304,29 +288,23 @@ public class TLAPrinter extends DepthFirstAdapter { } private void printExtendedModules() { - if (usedStandardModules.getExtendedModules().size() > 0) { + List<String> extendedModules = usedStandardModules.getExtendedModules(); + if (!extendedModules.isEmpty()) { moduleStringAppend("EXTENDS "); - for (int i = 0; i < usedStandardModules.getExtendedModules().size(); i++) { - if (i > 0) { - moduleStringAppend(", "); - } - moduleStringAppend(usedStandardModules.getExtendedModules() - .get(i).toString()); - } + moduleStringAppend(String.join(", ", extendedModules)); moduleStringAppend("\n"); } } private void printDefinitions() { ArrayList<TLADefinition> definitions = tlaModule.getTLADefinitions(); - for (int i = 0; i < definitions.size(); i++) { - TLADefinition def = definitions.get(i); + for (TLADefinition def : definitions) { if (def.getDefName() instanceof AEnumeratedSetSet) { def.getDefName().apply(this); continue; } def.getDefName().apply(this); - + moduleStringAppend(" == "); Node e = def.getDefinition(); if (e == null) { @@ -363,9 +341,9 @@ public class TLAPrinter extends DepthFirstAdapter { } moduleStringAppend("\n"); } - /******************/ + /* *************** */ ArrayList<Node> list = this.tlaModule.getConstants(); - if (list.size() == 0) + if (list.isEmpty()) return; moduleStringAppend("CONSTANTS "); for (int i = 0; i < list.size(); i++) { @@ -380,14 +358,13 @@ public class TLAPrinter extends DepthFirstAdapter { private void printAssume() { ArrayList<Node> list = this.tlaModule.getAssume(); - if (list.size() == 0) + if (list.isEmpty()) return; - for (int i = 0; i < list.size(); i++) { - Node node = list.get(i); - if(!typeRestrictor.isARemovedNode(node)){ + for (Node node : list) { + if (!typeRestrictor.isARemovedNode(node)) { moduleStringAppend("ASSUME "); - list.get(i).apply(this); + node.apply(this); moduleStringAppend("\n"); } } @@ -396,7 +373,7 @@ public class TLAPrinter extends DepthFirstAdapter { private void printVariables() { ArrayList<Node> vars = this.tlaModule.getVariables(); - if (vars.size() == 0) + if (vars.isEmpty()) return; moduleStringAppend("VARIABLES "); for (int i = 0; i < vars.size(); i++) { @@ -430,7 +407,7 @@ public class TLAPrinter extends DepthFirstAdapter { if (TLC4BGlobals.isPartialInvariantEvaluation()) { ArrayList<Node> operations = invariantPreservationAnalysis .getPreservingOperations(inv); - if (operations.size() > 0) { + if (!operations.isEmpty()) { moduleStringAppend("last_action \\in {"); for (int j = 0; j < operations.size(); j++) { Node op = operations.get(j); @@ -452,7 +429,7 @@ public class TLAPrinter extends DepthFirstAdapter { private void printAssertions() { if (TLC4BGlobals.isAssertion()) { ArrayList<Node> assertions = tlaModule.getAssertions(); - if (assertions.size() == 0) + if (assertions.isEmpty()) return; for (int i = 0; i < assertions.size(); i++) { Node assertion = assertions.get(i); @@ -466,14 +443,11 @@ public class TLAPrinter extends DepthFirstAdapter { name = "Assertion" + (i + 1); } - if (tlaModule.hasInitPredicate()) { - moduleStringAppend(name); - moduleStringAppend(" == "); - } else { + if (!tlaModule.hasInitPredicate()) { moduleStringAppend("ASSUME "); - moduleStringAppend(name); - moduleStringAppend(" == "); } + moduleStringAppend(name); + moduleStringAppend(" == "); // assertionMode = true; // assertionName = name; // parameterCounter = 0; @@ -485,12 +459,12 @@ public class TLAPrinter extends DepthFirstAdapter { } private static boolean assertionMode = false; - private static String assertionName = null; + private static final String assertionName = null; private static Integer parameterCounter = 0; private void printInit() { ArrayList<Node> inits = this.tlaModule.getInitPredicates(); - if (inits.size() == 0) + if (inits.isEmpty()) return; moduleStringAppend("Init == "); if (inits.size() > 1) @@ -515,9 +489,9 @@ public class TLAPrinter extends DepthFirstAdapter { private void printOperations() { ArrayList<POperation> ops = this.tlaModule.getOperations(); - if (ops.size() == 0) { + if (ops.isEmpty()) { ArrayList<Node> vars = tlaModule.getVariables(); - if (vars.size() > 0) { + if (!vars.isEmpty()) { moduleStringAppend("Next == 1 = 2 /\\ UNCHANGED <<"); for (int i = 0; i < vars.size(); i++) { vars.get(i).apply(this); @@ -529,8 +503,8 @@ public class TLAPrinter extends DepthFirstAdapter { } return; } - for (int i = 0; i < ops.size(); i++) { - ops.get(i).apply(this); + for (POperation op : ops) { + op.apply(this); } moduleStringAppend("Next == \\/ "); Iterator<Node> itr = this.machineContext.getOperations().values() @@ -548,17 +522,15 @@ public class TLAPrinter extends DepthFirstAdapter { public void printOperationCall(Node operation) { AOperation op = (AOperation) operation; - List<PExpression> newList = new ArrayList<PExpression>(); - newList.addAll(op.getParameters()); + List<PExpression> newList = new ArrayList<>(op.getParameters()); // newList.addAll(op.getReturnValues()); - if (newList.size() > 0) { + if (!newList.isEmpty()) { moduleStringAppend("\\E "); for (int i = 0; i < newList.size(); i++) { PExpression e = newList.get(i); e.apply(this); moduleStringAppend(" \\in "); typeRestrictor.getRestrictedNode(e).apply(this); - ; if (i < newList.size() - 1) { moduleStringAppend(", "); } @@ -568,7 +540,7 @@ public class TLAPrinter extends DepthFirstAdapter { String opName = renamer.getNameOfRef(op); moduleStringAppend(opName); - if (newList.size() > 0) { + if (!newList.isEmpty()) { moduleStringAppend("("); for (int i = 0; i < newList.size(); i++) { newList.get(i).apply(this); @@ -604,15 +576,13 @@ public class TLAPrinter extends DepthFirstAdapter { inAMachineHeader(node); moduleStringAppend(node.toString()); { - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>( - node.getName()); + List<TIdentifierLiteral> copy = new ArrayList<>(node.getName()); for (TIdentifierLiteral e : copy) { e.apply(this); } } { - List<PExpression> copy = new ArrayList<PExpression>( - node.getParameters()); + List<PExpression> copy = new ArrayList<>(node.getParameters()); for (PExpression e : copy) { e.apply(this); } @@ -622,7 +592,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAEnumeratedSetSet(AEnumeratedSetSet node) { - List<PExpression> copy = new ArrayList<PExpression>(node.getElements()); + List<PExpression> copy = new ArrayList<>(node.getElements()); moduleStringAppend(renamer.getNameOfRef(node) + " == {"); for (int i = 0; i < copy.size(); i++) { copy.get(i).apply(this); @@ -645,10 +615,8 @@ public class TLAPrinter extends DepthFirstAdapter { */ @Override - public void caseABecomesElementOfSubstitution( - ABecomesElementOfSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + public void caseABecomesElementOfSubstitution(ABecomesElementOfSubstitution node) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (int i = 0; i < copy.size(); i++) { if (i != 0) { moduleStringAppend(" /\\ "); @@ -662,10 +630,8 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAAssignSubstitution(AAssignSubstitution node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getLhsExpression()); - List<PExpression> copy2 = new ArrayList<PExpression>( - node.getRhsExpressions()); + List<PExpression> copy = new ArrayList<>(node.getLhsExpression()); + List<PExpression> copy2 = new ArrayList<>(node.getRhsExpressions()); for (int i = 0; i < copy.size(); i++) { PExpression left = copy.get(i); @@ -692,8 +658,7 @@ public class TLAPrinter extends DepthFirstAdapter { if (node.getPredicate() instanceof AExistsPredicate) { node.getPredicate().apply(this); } else { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (int i = 0; i < copy.size(); i++) { PExpression e = copy.get(i); @@ -729,12 +694,11 @@ public class TLAPrinter extends DepthFirstAdapter { private void printFunctionAssignment(PExpression left, PExpression right) { PExpression var = ((AFunctionExpression) left).getIdentifier(); - LinkedList<PExpression> params = ((AFunctionExpression) left) - .getParameters(); + LinkedList<PExpression> params = ((AFunctionExpression) left).getParameters(); BType type = typechecker.getType(var); + var.apply(this); + moduleStringAppend("' = "); if (type instanceof FunctionType) { - var.apply(this); - moduleStringAppend("' = "); moduleStringAppend(FUNC_ASSIGN); moduleStringAppend("("); var.apply(this); @@ -744,7 +708,7 @@ public class TLAPrinter extends DepthFirstAdapter { } for (Iterator<PExpression> iterator = params.iterator(); iterator .hasNext();) { - PExpression pExpression = (PExpression) iterator.next(); + PExpression pExpression = iterator.next(); pExpression.apply(this); if (iterator.hasNext()) { moduleStringAppend(", "); @@ -757,17 +721,14 @@ public class TLAPrinter extends DepthFirstAdapter { right.apply(this); moduleStringAppend(")"); } else { - var.apply(this); - moduleStringAppend("' = "); moduleStringAppend(REL_OVERRIDING + "("); var.apply(this); moduleStringAppend(", {<<"); if (params.size() > 1) { moduleStringAppend("<<"); - for (Iterator<PExpression> iterator = params.iterator(); iterator - .hasNext();) { - PExpression pExpression = (PExpression) iterator.next(); + for (Iterator<PExpression> iterator = params.iterator(); iterator.hasNext();) { + PExpression pExpression = iterator.next(); pExpression.apply(this); if (iterator.hasNext()) { moduleStringAppend(", "); @@ -784,12 +745,11 @@ public class TLAPrinter extends DepthFirstAdapter { } public void printUnchangedVariables(Node node, boolean printAnd) { - HashSet<Node> unchangedVariablesSet = missingVariableFinder - .getUnchangedVariables(node); + HashSet<Node> unchangedVariablesSet = missingVariableFinder.getUnchangedVariables(node); if (null != unchangedVariablesSet) { - ArrayList<Node> unchangedVariables = new ArrayList<Node>( - unchangedVariablesSet); - if (unchangedVariables.size() > 0) { + ArrayList<Node> unchangedVariables = new ArrayList<>( + unchangedVariablesSet); + if (!unchangedVariables.isEmpty()) { if (printAnd) { moduleStringAppend(" /\\"); } @@ -812,8 +772,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAChoiceSubstitution(AChoiceSubstitution node) { - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getSubstitutions()); moduleStringAppend("("); for (int i = 0; i < copy.size(); i++) { moduleStringAppend("("); @@ -835,16 +794,15 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAIfSubstitution(AIfSubstitution node) { - if (node.getElsifSubstitutions().size() > 0) { - printElseIFSubsitution(node); + if (!node.getElsifSubstitutions().isEmpty()) { + printElseIFSubstitution(node); return; } moduleStringAppend("(IF "); node.getCondition().apply(this); moduleStringAppend(" THEN "); node.getThen().apply(this); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getElsifSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getElsifSubstitutions()); for (PSubstitution e : copy) { e.apply(this); } @@ -859,13 +817,12 @@ public class TLAPrinter extends DepthFirstAdapter { printUnchangedVariables(node, true); } - private void printElseIFSubsitution(AIfSubstitution node) { + private void printElseIFSubstitution(AIfSubstitution node) { moduleStringAppend("(CASE "); node.getCondition().apply(this); moduleStringAppend(" -> "); node.getThen().apply(this); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getElsifSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getElsifSubstitutions()); for (PSubstitution e : copy) { moduleStringAppend(" [] "); e.apply(this); @@ -887,16 +844,14 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend(" -> "); node.getThenSubstitution().apply(this); printUnchangedVariables(node, true); - } public void printUnchangedVariablesNull(Node node, boolean printAnd) { - HashSet<Node> unchangedVariablesSet = missingVariableFinder - .getUnchangedVariablesNull(node); + HashSet<Node> unchangedVariablesSet = missingVariableFinder.getUnchangedVariablesNull(node); if (null != unchangedVariablesSet) { - ArrayList<Node> unchangedVariables = new ArrayList<Node>( - unchangedVariablesSet); - if (unchangedVariables.size() > 0) { + ArrayList<Node> unchangedVariables = new ArrayList<>( + unchangedVariablesSet); + if (!unchangedVariables.isEmpty()) { if (printAnd) { moduleStringAppend(" /\\"); } @@ -915,8 +870,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAParallelSubstitution(AParallelSubstitution node) { inAParallelSubstitution(node); - for (Iterator<PSubstitution> itr = node.getSubstitutions().iterator(); itr - .hasNext();) { + for (Iterator<PSubstitution> itr = node.getSubstitutions().iterator(); itr.hasNext();) { PSubstitution e = itr.next(); e.apply(this); @@ -956,15 +910,14 @@ public class TLAPrinter extends DepthFirstAdapter { inASelectSubstitution(node); // TODO remove brackets moduleStringAppend("("); - List<PSubstitution> copy = new ArrayList<PSubstitution>( - node.getWhenSubstitutions()); + List<PSubstitution> copy = new ArrayList<>(node.getWhenSubstitutions()); if (missingVariableFinder.hasUnchangedVariables(node) - && (copy.size() > 0 || node.getElse() != null)) { + && (!copy.isEmpty() || node.getElse() != null)) { moduleStringAppend("("); } if (!typeRestrictor.isARemovedNode(node.getCondition())) { - if (copy.size() > 0 || node.getElse() != null) { + if (!copy.isEmpty() || node.getElse() != null) { moduleStringAppend("("); } node.getCondition().apply(this); @@ -972,7 +925,7 @@ public class TLAPrinter extends DepthFirstAdapter { } node.getThen().apply(this); if (!typeRestrictor.isARemovedNode(node.getCondition())) { - if (copy.size() > 0 || node.getElse() != null) { + if (!copy.isEmpty() || node.getElse() != null) { moduleStringAppend(")"); } } @@ -996,7 +949,7 @@ public class TLAPrinter extends DepthFirstAdapter { } if (missingVariableFinder.hasUnchangedVariables(node) - && (copy.size() > 0 || node.getElse() != null)) { + && (!copy.isEmpty() || node.getElse() != null)) { moduleStringAppend(")"); } moduleStringAppend(")"); @@ -1017,9 +970,8 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAAnySubstitution(AAnySubstitution node) { inAAnySubstitution(node); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - if (copy.size() > 0) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + if (!copy.isEmpty()) { moduleStringAppend("\\E "); for (int i = 0; i < copy.size(); i++) { PExpression e = copy.get(i); @@ -1047,9 +999,8 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseALetSubstitution(ALetSubstitution node) { inALetSubstitution(node); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - if (copy.size() > 0) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + if (!copy.isEmpty()) { moduleStringAppend("\\E "); for (int i = 0; i < copy.size(); i++) { PExpression e = copy.get(i); @@ -1084,13 +1035,11 @@ public class TLAPrinter extends DepthFirstAdapter { // TODO handle output parameter of a operation // List<PExpression> output = new ArrayList<PExpression>( // node.getReturnValues()); - List<PExpression> params = new ArrayList<PExpression>( - node.getParameters()); - List<PExpression> newList = new ArrayList<PExpression>(); - newList.addAll(params); + List<PExpression> params = new ArrayList<>(node.getParameters()); + List<PExpression> newList = new ArrayList<>(params); // newList.addAll(output); - if (newList.size() > 0) { + if (!newList.isEmpty()) { moduleStringAppend("("); for (int i = 0; i < newList.size(); i++) { if (i != 0) { @@ -1117,9 +1066,9 @@ public class TLAPrinter extends DepthFirstAdapter { } private void printUnchangedConstants() { - ArrayList<Node> vars = new ArrayList<Node>(tlaModule.getVariables()); + ArrayList<Node> vars = new ArrayList<>(tlaModule.getVariables()); vars.removeAll(machineContext.getVariables().values()); - if (vars.size() > 0) { + if (!vars.isEmpty()) { moduleStringAppend(" /\\ UNCHANGED <<"); for (int i = 0; i < vars.size(); i++) { if (i != 0) @@ -1140,7 +1089,7 @@ public class TLAPrinter extends DepthFirstAdapter { if (name == null) { name = Utils.getTIdentifierListAsString(node.getIdentifier()); } - if (StandardMadules.isAbstractConstant(name)) { + if (StandardModules.isAbstractConstant(name)) { // in order to pass the member check moduleStringAppend("{}"); return; @@ -1165,7 +1114,7 @@ public class TLAPrinter extends DepthFirstAdapter { public void caseAStringExpression(AStringExpression node) { inAStringExpression(node); moduleStringAppend("\""); - moduleStringAppend(node.getContent().getText().toString()); + moduleStringAppend(node.getContent().getText()); moduleStringAppend("\""); outAStringExpression(node); } @@ -1282,14 +1231,12 @@ public class TLAPrinter extends DepthFirstAdapter { * B: !x,y(T => P) TLA: \A x \in type(x), y \in type(y): T => P */ inAForallPredicate(node); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); int start = parameterCounter; int end = parameterCounter + copy.size(); parameterCounter = end + 1; if (assertionMode) { - moduleStringAppend("("); moduleStringAppend("TLCSet("); moduleStringAppend("" + start); @@ -1364,8 +1311,7 @@ public class TLAPrinter extends DepthFirstAdapter { inAExistsPredicate(node); moduleStringAppend("\\E "); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); for (int i = 0; i < copy.size(); i++) { PExpression e = copy.get(i); e.apply(this); @@ -1404,8 +1350,7 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseAPredicateDefinitionDefinition( - APredicateDefinitionDefinition node) { + public void caseAPredicateDefinitionDefinition(APredicateDefinitionDefinition node) { String name = renamer.getNameOfRef(node); if (null == name) { name = node.getName().getText().trim(); @@ -1414,10 +1359,9 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseAExpressionDefinitionDefinition( - AExpressionDefinitionDefinition node) { + public void caseAExpressionDefinitionDefinition(AExpressionDefinitionDefinition node) { String oldName = node.getName().getText().trim(); - if (StandardMadules.isKeywordInModuleExternalFunctions(oldName)) { + if (StandardModules.isKeywordInModuleExternalFunctions(oldName)) { return; } String name = renamer.getName(node); @@ -1426,7 +1370,7 @@ public class TLAPrinter extends DepthFirstAdapter { } moduleStringAppend(name); List<PExpression> args = node.getParameters(); - if (args.size() > 0) { + if (!args.isEmpty()) { moduleStringAppend("("); for (int i = 0; i < args.size(); i++) { if (i != 0) @@ -1449,8 +1393,7 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseASubstitutionDefinitionDefinition( - ASubstitutionDefinitionDefinition node) { + public void caseASubstitutionDefinitionDefinition(ASubstitutionDefinitionDefinition node) { String name = renamer.getNameOfRef(node); if (null == name) { name = node.getName().getText().trim(); @@ -1458,13 +1401,12 @@ public class TLAPrinter extends DepthFirstAdapter { printBDefinition(name, node.getParameters(), node.getRhs()); } - private void printBDefinition(String name, List<PExpression> args, - Node rightSide) { - if (StandardMadules.isKeywordInModuleExternalFunctions(name)) { + private void printBDefinition(String name, List<PExpression> args, Node rightSide) { + if (StandardModules.isKeywordInModuleExternalFunctions(name)) { return; } moduleStringAppend(name); - if (args.size() > 0) { + if (!args.isEmpty()) { moduleStringAppend("("); for (int i = 0; i < args.size(); i++) { if (i != 0) @@ -1508,7 +1450,7 @@ public class TLAPrinter extends DepthFirstAdapter { public void printBDefinitionCall(String name, List<PExpression> args) { moduleStringAppend(name); - if (args.size() > 0) { + if (!args.isEmpty()) { moduleStringAppend("("); for (int i = 0; i < args.size(); i++) { if (i != 0) @@ -1548,8 +1490,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAIntSetExpression(AIntSetExpression node) { inAIntSetExpression(node); - moduleStringAppend("(" + TLC4BGlobals.getMIN_INT() + ".." - + TLC4BGlobals.getMAX_INT() + ")"); + moduleStringAppend("(" + TLC4BGlobals.getMIN_INT() + ".." + TLC4BGlobals.getMAX_INT() + ")"); outAIntSetExpression(node); } @@ -1671,7 +1612,6 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAModuloExpression(AModuloExpression node) { - inAModuloExpression(node); moduleStringAppend(B_MODULO); moduleStringAppend("("); @@ -1684,8 +1624,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAGeneralProductExpression(AGeneralProductExpression node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); moduleStringAppend("Pi("); moduleStringAppend("{"); moduleStringAppend("<<"); @@ -1716,8 +1655,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAGeneralSumExpression(AGeneralSumExpression node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); moduleStringAppend("Sigma("); moduleStringAppend("{"); moduleStringAppend("<<"); @@ -1811,7 +1749,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseALambdaExpression(ALambdaExpression node) { - /** + /* * B: %a,b.(P|e) TLA+ function: [<<a,b>> \in {<<a,b>> \in * type(a)*type(b) : P}|e] relation: TLA+: {<< <<a,b>>, e>>: <<a,b>> \in * {<<a,b>> \in type(a)*type(b): P}} @@ -1819,8 +1757,8 @@ public class TLAPrinter extends DepthFirstAdapter { inALambdaExpression(node); if (this.typechecker.getType(node) instanceof SetType) { moduleStringAppend("{<<"); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>( + node.getIdentifiers()); printIdentifierList(copy); moduleStringAppend(", "); node.getExpression().apply(this); @@ -1845,8 +1783,8 @@ public class TLAPrinter extends DepthFirstAdapter { } else { moduleStringAppend("["); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>( + node.getIdentifiers()); printIdentifierList(copy); moduleStringAppend(" \\in "); @@ -1879,13 +1817,13 @@ public class TLAPrinter extends DepthFirstAdapter { AIdentifierExpression id = (AIdentifierExpression) node .getIdentifier(); String name = Utils.getTIdentifierListAsString(id.getIdentifier()); - if (StandardMadules.isAbstractConstant(name)) { + if (StandardModules.isAbstractConstant(name)) { moduleStringAppend(name); // node.getIdentifier().apply(this); moduleStringAppend("("); - List<PExpression> copy = new ArrayList<PExpression>( - node.getParameters()); + List<PExpression> copy = new ArrayList<>( + node.getParameters()); copy.get(0).apply(this); moduleStringAppend(")"); return; @@ -1898,8 +1836,8 @@ public class TLAPrinter extends DepthFirstAdapter { if (type instanceof FunctionType) { node.getIdentifier().apply(this); moduleStringAppend("["); - List<PExpression> copy = new ArrayList<PExpression>( - node.getParameters()); + List<PExpression> copy = new ArrayList<>( + node.getParameters()); for (int i = 0; i < copy.size(); i++) { if (i != 0) { moduleStringAppend(", "); @@ -1917,8 +1855,8 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend("("); node.getIdentifier().apply(this); moduleStringAppend(", "); - List<PExpression> copy = new ArrayList<PExpression>( - node.getParameters()); + List<PExpression> copy = new ArrayList<>( + node.getParameters()); if (copy.size() > 1) moduleStringAppend("<<"); for (int i = 0; i < copy.size(); i++) { @@ -2005,8 +1943,8 @@ public class TLAPrinter extends DepthFirstAdapter { } } - private void setOfFuntions(Node node, String funcName, String relName, - String relEleOfName, Node left, Node right) { + private void setOfFunctions(Node node, String funcName, String relName, + String relEleOfName, Node left, Node right) { BType type = this.typechecker.getType(node); BType subtype = ((SetType) type).getSubtype(); if (subtype instanceof FunctionType) { @@ -2027,7 +1965,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseATotalInjectionExpression(ATotalInjectionExpression node) { - setOfFuntions(node, TOTAL_INJECTIVE_FUNCTION, + setOfFunctions(node, TOTAL_INJECTIVE_FUNCTION, REL_TOTAL_INJECTIVE_FUNCTION, REL_TOTAL_INJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), node.getRight()); @@ -2035,7 +1973,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseATotalSurjectionExpression(ATotalSurjectionExpression node) { - setOfFuntions(node, TOTAL_SURJECTIVE_FUNCTION, + setOfFunctions(node, TOTAL_SURJECTIVE_FUNCTION, REL_TOTAL_SURJECTIVE_FUNCTION, REL_TOTAL_SURJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), node.getRight()); @@ -2043,15 +1981,15 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseATotalBijectionExpression(ATotalBijectionExpression node) { - setOfFuntions(node, TOTAL_BIJECTIVE_FUNCTION, + setOfFunctions(node, TOTAL_BIJECTIVE_FUNCTION, REL_TOTAL_BIJECTIVE_FUNCTION, REL_TOTAL_BIJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), node.getRight()); } - private void setOfPartialFuntions(Node node, String funcName, - String funcEleOfName, String relName, String relEleOfName, - Node left, Node right) { + private void setOfPartialFunctions(Node node, String funcName, + String funcEleOfName, String relName, String relEleOfName, + Node left, Node right) { BType type = this.typechecker.getType(node); BType subtype = ((SetType) type).getSubtype(); if (subtype instanceof FunctionType) { @@ -2086,7 +2024,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAPartialFunctionExpression(APartialFunctionExpression node) { - setOfPartialFuntions(node, PARTIAL_FUNCTION, + setOfPartialFunctions(node, PARTIAL_FUNCTION, PARTIAL_FUNCTION_ELEMENT_OF, REL_PARTIAL_FUNCTION, REL_PARTIAL_FUNCTION_ELEMENT_OF, node.getLeft(), node.getRight()); @@ -2094,7 +2032,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAPartialInjectionExpression(APartialInjectionExpression node) { - setOfPartialFuntions(node, PARTIAL_INJECTIVE_FUNCTION, + setOfPartialFunctions(node, PARTIAL_INJECTIVE_FUNCTION, PARTIAL_INJECTIVE_FUNCTION_ELEMENT_OF, REL_PARTIAL_INJECTIVE_FUNCTION, REL_PARTIAL_INJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), @@ -2102,9 +2040,8 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseAPartialSurjectionExpression( - APartialSurjectionExpression node) { - setOfPartialFuntions(node, PARTIAL_SURJECTIVE_FUNCTION, + public void caseAPartialSurjectionExpression(APartialSurjectionExpression node) { + setOfPartialFunctions(node, PARTIAL_SURJECTIVE_FUNCTION, PARTIAL_SURJECTIVE_FUNCTION_ELEMENT_OF, REL_PARTIAL_SURJECTIVE_FUNCTION, REL_PARTIAL_SURJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), @@ -2113,8 +2050,8 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAPartialBijectionExpression(APartialBijectionExpression node) { - setOfPartialFuntions(node, PARITAL_BIJECTIVE_FUNCTION, - PARITAL_BIJECTIVE_FUNCTION_ELEMENT_OF, + setOfPartialFunctions(node, PARTIAL_BIJECTIVE_FUNCTION, + PARTIAL_BIJECTIVE_FUNCTION_ELEMENT_OF, REL_PARTIAL_BIJECTIVE_FUNCTION, REL_PARTIAL_BIJECTIVE_FUNCTION_ELEMENT_OF, node.getLeft(), node.getRight()); @@ -2147,8 +2084,8 @@ public class TLAPrinter extends DepthFirstAdapter { } moduleStringAppend("{"); { - List<PExpression> copy = new ArrayList<PExpression>( - node.getExpressions()); + List<PExpression> copy = new ArrayList<>( + node.getExpressions()); for (int i = 0; i < copy.size(); i++) { if (i != 0) { moduleStringAppend(", "); @@ -2161,11 +2098,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAEmptySetExpression(AEmptySetExpression node) { - if (typechecker.getType(node) instanceof FunctionType) { - moduleStringAppend("<< >>"); - } else { - moduleStringAppend("{}"); - } + evalEmptyFunctionOrRelation(node); } @Override @@ -2189,8 +2122,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAComprehensionSetExpression(AComprehensionSetExpression node) { inAComprehensionSetExpression(node); - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); if (copy.size() < 3) { moduleStringAppend("{"); printIdentifierList(copy); @@ -2232,8 +2164,7 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseAEventBComprehensionSetExpression( - AEventBComprehensionSetExpression node) { + public void caseAEventBComprehensionSetExpression(AEventBComprehensionSetExpression node) { inAEventBComprehensionSetExpression(node); moduleStringAppend("{"); @@ -2387,8 +2318,7 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseAGeneralIntersectionExpression( - AGeneralIntersectionExpression node) { + public void caseAGeneralIntersectionExpression(AGeneralIntersectionExpression node) { inAGeneralIntersectionExpression(node); moduleStringAppend("Inter("); node.getExpression().apply(this); @@ -2398,8 +2328,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAQuantifiedUnionExpression(AQuantifiedUnionExpression node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); moduleStringAppend("UNION({"); node.getExpression().apply(this); @@ -2409,7 +2338,6 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend(" \\in "); printTypesOfIdentifierList(copy); moduleStringAppend("})"); - return; } else { moduleStringAppend(" \\in {"); printIdentifierList(copy); @@ -2420,14 +2348,11 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend("}"); moduleStringAppend("})"); } - } @Override - public void caseAQuantifiedIntersectionExpression( - AQuantifiedIntersectionExpression node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); + public void caseAQuantifiedIntersectionExpression(AQuantifiedIntersectionExpression node) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); moduleStringAppend("Inter({"); node.getExpression().apply(this); @@ -2437,7 +2362,6 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend(" \\in "); printTypesOfIdentifierList(copy); moduleStringAppend("})"); - return; } else { moduleStringAppend(" \\in {"); printIdentifierList(copy); @@ -2457,7 +2381,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseACoupleExpression(ACoupleExpression node) { inACoupleExpression(node); - List<PExpression> copy = new ArrayList<PExpression>(node.getList()); + List<PExpression> copy = new ArrayList<>(node.getList()); for (int i = 0; i < copy.size() - 1; i++) { moduleStringAppend("<<"); } @@ -2511,8 +2435,7 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseADomainRestrictionExpression( - ADomainRestrictionExpression node) { + public void caseADomainRestrictionExpression(ADomainRestrictionExpression node) { if (typechecker.getType(node) instanceof FunctionType) { moduleStringAppend(FUNC_DOMAIN_RESTRICTION); } else { @@ -2526,12 +2449,11 @@ public class TLAPrinter extends DepthFirstAdapter { } @Override - public void caseADomainSubtractionExpression( - ADomainSubtractionExpression node) { + public void caseADomainSubtractionExpression(ADomainSubtractionExpression node) { if (typechecker.getType(node) instanceof FunctionType) { - moduleStringAppend(FUNC_DOMAIN_SUBSTRACTION); + moduleStringAppend(FUNC_DOMAIN_SUBTRACTION); } else { - moduleStringAppend(REL_DOMAIN_SUBSTRACTION); + moduleStringAppend(REL_DOMAIN_SUBTRACTION); } moduleStringAppend("("); node.getLeft().apply(this); @@ -2557,9 +2479,9 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseARangeSubtractionExpression(ARangeSubtractionExpression node) { if (typechecker.getType(node) instanceof FunctionType) { - moduleStringAppend(FUNC_RANGE_SUBSTRACTION); + moduleStringAppend(FUNC_RANGE_SUBTRACTION); } else { - moduleStringAppend(REL_RANGE_SUBSTRACTION); + moduleStringAppend(REL_RANGE_SUBTRACTION); } moduleStringAppend("("); node.getLeft().apply(this); @@ -2691,10 +2613,8 @@ public class TLAPrinter extends DepthFirstAdapter { */ @Override - public void caseASequenceExtensionExpression( - ASequenceExtensionExpression node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getExpression()); + public void caseASequenceExtensionExpression(ASequenceExtensionExpression node) { + List<PExpression> copy = new ArrayList<>(node.getExpression()); BType type = typechecker.getType(node); if (type instanceof FunctionType) { moduleStringAppend("<<"); @@ -2720,19 +2640,13 @@ public class TLAPrinter extends DepthFirstAdapter { } } - private void evalFunctionOrRelation(Node node, String function, - String relation) { - BType type = typechecker.getType(node); - if (type instanceof FunctionType) { - moduleStringAppend(function); - } else { - moduleStringAppend(relation); - } + private void evalEmptyFunctionOrRelation(Node node) { + moduleStringAppend(typechecker.getType(node) instanceof FunctionType ? "<<>>" : "{}"); } @Override public void caseAEmptySequenceExpression(AEmptySequenceExpression node) { - evalFunctionOrRelation(node, "<<>>", "{}"); + evalEmptyFunctionOrRelation(node); } @Override @@ -2776,11 +2690,11 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAInsertTailExpression(AInsertTailExpression node) { printSequenceOrRelation(node, "Append", REL_SEQUENCE_APPEND, - node.getLeft(), node.getRight()); + node.getLeft(), node.getRight()); } private void printSequenceOrRelation(Node node, String sequence, - String relation, Node left, Node right) { + String relation, Node left, Node right) { BType type = typechecker.getType(node); if (type instanceof SetType) { moduleStringAppend(relation); @@ -2880,7 +2794,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseAInsertFrontExpression(AInsertFrontExpression node) { printSequenceOrRelation(node.getRight(), SEQUENCE_PREPEND_ELEMENT, - REL_SEQUENCE_PREPAND, node.getLeft(), node.getRight()); + REL_SEQUENCE_PREPEND, node.getLeft(), node.getRight()); } @Override @@ -2922,8 +2836,8 @@ public class TLAPrinter extends DepthFirstAdapter { typechecker.unify(expected2, result, node); } - printSequenceOrRelation(node, SEQUENCE_GENERAL_CONCATINATION, - REL_SEQUENCE_GENERAL_CONCATINATION, node.getExpression(), null); + printSequenceOrRelation(node, SEQUENCE_GENERAL_CONCATENATION, + REL_SEQUENCE_GENERAL_CONCATENATION, node.getExpression(), null); } @Override @@ -2944,8 +2858,7 @@ public class TLAPrinter extends DepthFirstAdapter { * Special Operator */ @Override - public void caseAMinusOrSetSubtractExpression( - AMinusOrSetSubtractExpression node) { + public void caseAMinusOrSetSubtractExpression(AMinusOrSetSubtractExpression node) { inAMinusOrSetSubtractExpression(node); node.getLeft().apply(this); @@ -3002,7 +2915,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseARecExpression(ARecExpression node) { moduleStringAppend("["); - List<PRecEntry> copy = new ArrayList<PRecEntry>(node.getEntries()); + List<PRecEntry> copy = new ArrayList<>(node.getEntries()); for (int i = 0; i < copy.size(); i++) { copy.get(i).apply(this); if (i < copy.size() - 1) { @@ -3014,7 +2927,7 @@ public class TLAPrinter extends DepthFirstAdapter { @Override public void caseARecEntry(ARecEntry node) { - node.getIdentifier().apply(this); + moduleStringAppend(node.getIdentifier().getText()); if (typechecker.getType(node.parent()) instanceof StructType) { moduleStringAppend(" |-> "); } else { @@ -3029,14 +2942,14 @@ public class TLAPrinter extends DepthFirstAdapter { inARecordFieldExpression(node); node.getRecord().apply(this); moduleStringAppend("."); - node.getIdentifier().apply(this); + moduleStringAppend(node.getIdentifier().getText()); outARecordFieldExpression(node); } @Override public void caseAStructExpression(AStructExpression node) { moduleStringAppend("["); - List<PRecEntry> copy = new ArrayList<PRecEntry>(node.getEntries()); + List<PRecEntry> copy = new ArrayList<>(node.getEntries()); for (int i = 0; i < copy.size(); i++) { copy.get(i).apply(this); if (i < copy.size() - 1) { @@ -3046,10 +2959,6 @@ public class TLAPrinter extends DepthFirstAdapter { moduleStringAppend("]"); } - public String geTranslatedLTLFormula() { - return this.translatedLTLFormula.toString(); - } - public TLAModule getTLAModule() { return this.tlaModule; } diff --git a/src/main/java/de/tlc4b/tla/ConfigFile.java b/src/main/java/de/tlc4b/tla/ConfigFile.java index 3f2ca06eb0eeafb17d8720bc39b2972664905f9e..456c37d07d71ba7beaf39a93fbf91598e53b2fb4 100644 --- a/src/main/java/de/tlc4b/tla/ConfigFile.java +++ b/src/main/java/de/tlc4b/tla/ConfigFile.java @@ -17,7 +17,7 @@ public class ConfigFile { public ConfigFile(){ - this.assignments = new ArrayList<ConfigFileAssignment>(); + this.assignments = new ArrayList<>(); this.invariantNumber = 0; } diff --git a/src/main/java/de/tlc4b/tla/Generator.java b/src/main/java/de/tlc4b/tla/Generator.java index 79d2e2fc56c6cd8639116383de57a4873de9155c..1cb5219b90d6ae20e159d186b54a537301d3672a 100644 --- a/src/main/java/de/tlc4b/tla/Generator.java +++ b/src/main/java/de/tlc4b/tla/Generator.java @@ -40,13 +40,13 @@ import de.tlc4b.tla.config.SetOfModelValuesAssignment; public class Generator extends DepthFirstAdapter { - private MachineContext machineContext; - private TypeRestrictor typeRestrictor; - private ConstantsEvaluator constantsEvaluator; - private DefinitionsAnalyser deferredSetSizeCalculator; + private final MachineContext machineContext; + private final TypeRestrictor typeRestrictor; + private final ConstantsEvaluator constantsEvaluator; + private final DefinitionsAnalyser deferredSetSizeCalculator; - private TLAModule tlaModule; - private ConfigFile configFile; + private final TLAModule tlaModule; + private final ConfigFile configFile; public Generator(MachineContext machineContext, TypeRestrictor typeRestrictor, @@ -92,37 +92,33 @@ public class Generator extends DepthFirstAdapter { private void evalSpec() { if (this.configFile.isInit() && this.configFile.isNext() && TLC4BGlobals.isCheckLTL() - && machineContext.getLTLFormulas().size() > 0) { + && !machineContext.getLTLFormulas().isEmpty()) { this.configFile.setSpec(); } } private void evalGoal() { if (TLC4BGlobals.isGOAL()) { - if (machineContext.getDefinitions().keySet().contains("GOAL")) { + if (machineContext.getDefinitions().containsKey("GOAL")) { this.configFile.setGoal(); } } } private void evalSetValuedParameter() { - /** + /* * For each set-valued parameter (first letter in upper case) we create * a TLA definition e.g. MACHINE Test(P) -> P == {P_1, P_2} */ - Iterator<String> itr = machineContext.getSetParamter().keySet() - .iterator(); - while (itr.hasNext()) { - String parameter = itr.next(); - Node node = machineContext.getSetParamter().get(parameter); + for (String parameter : machineContext.getSetParameter().keySet()) { + Node node = machineContext.getSetParameter().get(parameter); tlaModule.constants.add(node); configFile.addAssignment(new SetOfModelValuesAssignment(node, 3)); } - } private void evalScalarParameter() { - /** + /* * For each scalar-valued parameter we have to find out if it has a * determined value in the CONSTRAINT clause (e.g. p = 1). In this case * we create a TLA constant, in the other case we create a TLA variable @@ -130,7 +126,7 @@ public class Generator extends DepthFirstAdapter { */ Collection<Node> params = machineContext.getScalarParameter().values(); - if (params.size() == 0) + if (params.isEmpty()) return; LinkedHashMap<Node, Node> idValueTable = constantsEvaluator @@ -177,12 +173,10 @@ public class Generator extends DepthFirstAdapter { private void evalMachineSets() { /* - * Deffered Sets + * Deferred Sets */ LinkedHashMap<String, Node> map = machineContext.getDeferredSets(); - Iterator<Node> itr = map.values().iterator(); - while (itr.hasNext()) { - Node d = itr.next(); + for (Node d : map.values()) { tlaModule.constants.add(d); Integer size; size = deferredSetSizeCalculator.getSize(d); @@ -190,8 +184,7 @@ public class Generator extends DepthFirstAdapter { size = constantsEvaluator.getIntValue(d); } - this.configFile.addAssignment(new SetOfModelValuesAssignment(d, - size)); + this.configFile.addAssignment(new SetOfModelValuesAssignment(d, size)); } /* @@ -199,100 +192,81 @@ public class Generator extends DepthFirstAdapter { */ LinkedHashMap<String, Node> map2 = machineContext.getEnumeratedSets(); - Iterator<Node> itr2 = map2.values().iterator(); - while (itr2.hasNext()) { - Node n = itr2.next(); + for (Node n : map2.values()) { AEnumeratedSetSet e = (AEnumeratedSetSet) n; TLADefinition def = new TLADefinition(e, e); this.tlaModule.addTLADefinition(def); - List<PExpression> copy = new ArrayList<PExpression>(e.getElements()); + List<PExpression> copy = new ArrayList<>(e.getElements()); for (PExpression element : copy) { this.tlaModule.constants.add(element); - this.configFile - .addAssignment(new ModelValueAssignment(element)); + this.configFile.addAssignment(new ModelValueAssignment(element)); } } } private void evalDefinitions() { - ADefinitionsMachineClause node = machineContext - .getDefinitionMachineClause(); + ADefinitionsMachineClause node = machineContext.getDefinitionMachineClause(); if (node != null) { - ArrayList<PDefinition> bDefinitions = new ArrayList<PDefinition>( - node.getDefinitions()); - DefinitionsSorter defOrder = new DefinitionsSorter(machineContext, - bDefinitions); + ArrayList<PDefinition> bDefinitions = new ArrayList<>(node.getDefinitions()); + DefinitionsSorter defOrder = new DefinitionsSorter(machineContext, bDefinitions); this.tlaModule.allDefinitions.addAll(defOrder.getAllDefinitions()); } } private void evalOperations() { - AOperationsMachineClause node = machineContext - .getOperationMachineClause(); + AOperationsMachineClause node = machineContext.getOperationMachineClause(); if (null != node) { configFile.setNext(); - List<POperation> copy = new ArrayList<POperation>( - node.getOperations()); - for (POperation e : copy) { - this.tlaModule.operations.add(e); - } + List<POperation> copy = new ArrayList<>(node.getOperations()); + this.tlaModule.operations.addAll(copy); } } private void evalConstants() { if (machineContext.getPropertiesMachineClause() == null) return; - LinkedHashMap<Node, Node> conValueTable = constantsEvaluator - .getValueOfIdentifierMap(); - Iterator<Entry<Node, Node>> iterator = conValueTable.entrySet() - .iterator(); - while (iterator.hasNext()) { - Entry<Node, Node> entry = iterator.next(); + LinkedHashMap<Node, Node> conValueTable = constantsEvaluator.getValueOfIdentifierMap(); + for (Entry<Node, Node> entry : conValueTable.entrySet()) { AIdentifierExpression con = (AIdentifierExpression) entry.getKey(); Node value = entry.getValue(); AExpressionDefinitionDefinition exprDef = new AExpressionDefinitionDefinition( - con.getIdentifier().get(0), new LinkedList<PExpression>(), - (PExpression) value);// .clone()); + con.getIdentifier().get(0), new LinkedList<>(), + (PExpression) value + );// .clone()); machineContext.addReference(exprDef, con); this.tlaModule.addToAllDefinitions(exprDef); } - ArrayList<Node> remainingConstants = new ArrayList<Node>(); - remainingConstants.addAll(machineContext.getConstants().values()); + ArrayList<Node> remainingConstants = new ArrayList<>(machineContext.getConstants().values()); remainingConstants.removeAll(conValueTable.keySet()); - Node propertiesPerdicate = machineContext.getPropertiesMachineClause() - .getPredicates(); - if (remainingConstants.size() > 0) { + Node propertiesPredicate = machineContext.getPropertiesMachineClause().getPredicates(); + if (!remainingConstants.isEmpty()) { boolean init = false; int numberOfIteratedConstants = 0; - for (int i = 0; i < remainingConstants.size(); i++) { + for (Node remainingConstant : remainingConstants) { init = true; - Node con = remainingConstants.get(i); - this.tlaModule.variables.add(con); + this.tlaModule.variables.add(remainingConstant); - ArrayList<PExpression> rangeList = constantsEvaluator - .getRangeOfIdentifier(con); - if (rangeList.size() > 0) { + ArrayList<PExpression> rangeList = constantsEvaluator.getRangeOfIdentifier(remainingConstant); + if (!rangeList.isEmpty()) { numberOfIteratedConstants++; - ArrayList<PExpression> clone = new ArrayList<PExpression>(); + ArrayList<PExpression> clone = new ArrayList<>(); for (PExpression pExpression : rangeList) { - clone.add((PExpression) pExpression.clone()); + clone.add(pExpression.clone()); } - ASetExtensionExpression set = new ASetExtensionExpression( - clone); - AMemberPredicate member = new AMemberPredicate( - (AIdentifierExpression) con, set); + ASetExtensionExpression set = new ASetExtensionExpression(clone); + AMemberPredicate member = new AMemberPredicate((AIdentifierExpression) remainingConstant, set); tlaModule.addInit(member); continue; } - Node restrictedNode = typeRestrictor.getRestrictedNode(con); + Node restrictedNode = typeRestrictor.getRestrictedNode(remainingConstant); AMemberPredicate memberPredicate = new AMemberPredicate( - (PExpression) con, (PExpression) restrictedNode); + (PExpression) remainingConstant, (PExpression) restrictedNode); tlaModule.addInit(memberPredicate); } @@ -303,8 +277,8 @@ public class Generator extends DepthFirstAdapter { if (init) { configFile.setInit(); - if (!typeRestrictor.isARemovedNode(propertiesPerdicate)) - tlaModule.addInit(propertiesPerdicate); + if (!typeRestrictor.isARemovedNode(propertiesPredicate)) + tlaModule.addInit(propertiesPredicate); } } else { @@ -312,7 +286,7 @@ public class Generator extends DepthFirstAdapter { tlaModule.assumes .addAll(constantsEvaluator.getPropertiesList()); } - tlaModule.addAssume(propertiesPerdicate); + tlaModule.addAssume(propertiesPredicate); } } @@ -326,26 +300,19 @@ public class Generator extends DepthFirstAdapter { @Override public void caseAVariablesMachineClause(AVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - this.tlaModule.variables.add(e); - } + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + this.tlaModule.variables.addAll(copy); } @Override - public void caseAConcreteVariablesMachineClause( - AConcreteVariablesMachineClause node) { - List<PExpression> copy = new ArrayList<PExpression>( - node.getIdentifiers()); - for (PExpression e : copy) { - this.tlaModule.variables.add(e); - } + public void caseAConcreteVariablesMachineClause(AConcreteVariablesMachineClause node) { + List<PExpression> copy = new ArrayList<>(node.getIdentifiers()); + this.tlaModule.variables.addAll(copy); } @Override public void inAAssertionsMachineClause(AAssertionsMachineClause node) { - List<PPredicate> copy = new ArrayList<PPredicate>(node.getPredicates()); + List<PPredicate> copy = new ArrayList<>(node.getPredicates()); for (PPredicate e : copy) { this.tlaModule.addAssertion(e); } diff --git a/src/main/java/de/tlc4b/tla/TLADefinition.java b/src/main/java/de/tlc4b/tla/TLADefinition.java index 51c5df7e4a4994fdf66ef115a84eb9af5ab7d3fa..be347130d6dfda1daa9badd50ea70fd531b9bd45 100644 --- a/src/main/java/de/tlc4b/tla/TLADefinition.java +++ b/src/main/java/de/tlc4b/tla/TLADefinition.java @@ -3,7 +3,7 @@ package de.tlc4b.tla; import de.be4.classicalb.core.parser.node.Node; public class TLADefinition { - private Node name; + private final Node name; private Node definition; private Integer intValue; diff --git a/src/main/java/de/tlc4b/tla/TLAModule.java b/src/main/java/de/tlc4b/tla/TLAModule.java index 3d308319ec627616c6621f3630deb234438f4749..c3b162764eafadfed90afd6cb13c980d078f202b 100644 --- a/src/main/java/de/tlc4b/tla/TLAModule.java +++ b/src/main/java/de/tlc4b/tla/TLAModule.java @@ -19,20 +19,20 @@ public class TLAModule { private ArrayList<PDefinition> bDefinitions; private final ArrayList<Node> assertions; - protected ArrayList<PDefinition> allDefinitions; + protected final ArrayList<PDefinition> allDefinitions; public TLAModule() { - this.tlaDefinitions = new ArrayList<TLADefinition>(); - this.constants = new ArrayList<Node>(); - this.assumes = new ArrayList<Node>(); - this.variables = new ArrayList<Node>(); - this.initPredicates = new ArrayList<Node>(); - this.operations = new ArrayList<POperation>(); - this.bDefinitions = new ArrayList<PDefinition>(); - this.assertions = new ArrayList<Node>(); - this.invariants = new ArrayList<Node>(); + this.tlaDefinitions = new ArrayList<>(); + this.constants = new ArrayList<>(); + this.assumes = new ArrayList<>(); + this.variables = new ArrayList<>(); + this.initPredicates = new ArrayList<>(); + this.operations = new ArrayList<>(); + this.bDefinitions = new ArrayList<>(); + this.assertions = new ArrayList<>(); + this.invariants = new ArrayList<>(); - this.allDefinitions = new ArrayList<PDefinition>(); + this.allDefinitions = new ArrayList<>(); } @@ -107,10 +107,10 @@ public class TLAModule { } public boolean hasInitPredicate() { - return this.initPredicates.size() > 0; + return !this.initPredicates.isEmpty(); } - public void addTLADefinition(TLADefinition defintion) { - this.tlaDefinitions.add(defintion); + public void addTLADefinition(TLADefinition definition) { + this.tlaDefinitions.add(definition); } } diff --git a/src/main/java/de/tlc4b/tla/config/ConfigFileAssignment.java b/src/main/java/de/tlc4b/tla/config/ConfigFileAssignment.java index 4c4face506d164b5405701287ab2af0b75a2a4d1..64b0fafa49eb5626bcfb1d2fdbcd9cc87ef01421 100644 --- a/src/main/java/de/tlc4b/tla/config/ConfigFileAssignment.java +++ b/src/main/java/de/tlc4b/tla/config/ConfigFileAssignment.java @@ -12,9 +12,9 @@ public abstract class ConfigFileAssignment { public abstract String getString(Renamer renamer); public String getIdentifier(AIdentifierExpression node) { - StringBuffer res = new StringBuffer(); + StringBuilder res = new StringBuilder(); - List<TIdentifierLiteral> copy = new ArrayList<TIdentifierLiteral>( + List<TIdentifierLiteral> copy = new ArrayList<>( node.getIdentifier()); for (TIdentifierLiteral e : copy) { res.append(e.getText()); diff --git a/src/main/java/de/tlc4b/tla/config/ModelValueAssignment.java b/src/main/java/de/tlc4b/tla/config/ModelValueAssignment.java index 84c47528e2304e946c2a3deb4cf7b6dbd60a9c8b..a92f63620687d0e86a29aecc633c2c7d86087674 100644 --- a/src/main/java/de/tlc4b/tla/config/ModelValueAssignment.java +++ b/src/main/java/de/tlc4b/tla/config/ModelValueAssignment.java @@ -5,7 +5,7 @@ import de.be4.classicalb.core.parser.node.Node; import de.tlc4b.analysis.Renamer; public class ModelValueAssignment extends ConfigFileAssignment{ - private Node node; + private final Node node; public ModelValueAssignment(Node node){ this.node = node; @@ -13,8 +13,8 @@ public class ModelValueAssignment extends ConfigFileAssignment{ public String getString(Renamer renamer) { AIdentifierExpression id = (AIdentifierExpression) node; - String conString = getIdentifier(id); - conString = renamer.getNameOfRef(id); + getIdentifier(id); + String conString = renamer.getNameOfRef(id); return conString+ " = "+ conString +"\n"; } diff --git a/src/main/java/de/tlc4b/tla/config/SetOfModelValuesAssignment.java b/src/main/java/de/tlc4b/tla/config/SetOfModelValuesAssignment.java index d69bd9fdc36adf5db317e256970bad5deb82eb27..5d0607d6c77f1456d68f6c4dc31b68150a4657f2 100644 --- a/src/main/java/de/tlc4b/tla/config/SetOfModelValuesAssignment.java +++ b/src/main/java/de/tlc4b/tla/config/SetOfModelValuesAssignment.java @@ -17,8 +17,8 @@ import de.tlc4b.analysis.Renamer; */ public class SetOfModelValuesAssignment extends ConfigFileAssignment { - private Node node; - private int size; + private final Node node; + private final int size; public SetOfModelValuesAssignment(Node node, Integer size) { this.node = node; @@ -31,25 +31,25 @@ public class SetOfModelValuesAssignment extends ConfigFileAssignment { } public String getString(Renamer renamer) { - StringBuffer res = new StringBuffer(); + StringBuilder res = new StringBuilder(); - String conString; + StringBuilder conString; if (node instanceof ADeferredSetSet) { - conString = ""; + conString = new StringBuilder(); List<TIdentifierLiteral> copy = ((ADeferredSetSet) node) .getIdentifier(); for (TIdentifierLiteral e : copy) { - conString += e.getText(); + conString.append(e.getText()); } - conString = renamer.getName(node); + conString = new StringBuilder(renamer.getName(node)); } else { AIdentifierExpression id = (AIdentifierExpression) node; - conString = getIdentifier(id); + conString = new StringBuilder(getIdentifier(id)); } res.append(conString).append(" = {"); for (int j = 1; j < size + 1; j++) { - res.append(conString + j); + res.append(conString).append(j); if (j < size) { res.append(","); } diff --git a/src/main/java/de/tlc4b/tlc/ModuleMatcher.java b/src/main/java/de/tlc4b/tlc/ModuleMatcher.java index 477aee4e43b5c38722c094101aaa9ad7bfab5b65..0a82d3b1ac325df2a69ea762ec1292554f9cbf4d 100644 --- a/src/main/java/de/tlc4b/tlc/ModuleMatcher.java +++ b/src/main/java/de/tlc4b/tlc/ModuleMatcher.java @@ -16,7 +16,7 @@ public class ModuleMatcher { public ModuleMatcher(String fileName, String path) { this.fileName = fileName; - this.lineToNameMap = new HashMap<Integer, String>(); + this.lineToNameMap = new HashMap<>(); ModuleNode moduleNode = parse(fileName, path); evalActions(moduleNode); } @@ -26,15 +26,12 @@ public class ModuleMatcher { if(line == -1){ return "Init"; } - String res = lineToNameMap.get(line); - return res; + return lineToNameMap.get(line); } private void evalActions(ModuleNode moduleNode) { OpDefNode[] opdefs = moduleNode.getOpDefs(); - for (int i = 0; i < opdefs.length; i++) { - OpDefNode opdef = opdefs[i]; - + for (OpDefNode opdef : opdefs) { String module = opdef.getSource() .getOriginallyDefinedInModuleNode().getName().toString(); if (module.equalsIgnoreCase(fileName)) { @@ -84,7 +81,7 @@ public class ModuleMatcher { public static String allMessagesToString(String[] allMessages) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < allMessages.length - 1; i++) { - sb.append(allMessages[i] + "\n"); + sb.append(allMessages[i]).append("\n"); } return sb.toString(); } diff --git a/src/main/java/de/tlc4b/tlc/TLCMessageListener.java b/src/main/java/de/tlc4b/tlc/TLCMessageListener.java new file mode 100644 index 0000000000000000000000000000000000000000..d1f276a0f16cc859aa72fd3713946d39de098f50 --- /dev/null +++ b/src/main/java/de/tlc4b/tlc/TLCMessageListener.java @@ -0,0 +1,38 @@ +package de.tlc4b.tlc; + +import tlc2.output.Message; +import tlc2.output.OutputCollector; + +import java.util.*; + +public abstract class TLCMessageListener extends Thread { + private volatile boolean tlcRunning = true; + private final List<Message> messages = new ArrayList<>(); + private int lastMessageIndex = 0; + + @Override + public void run() { + while (tlcRunning) { + List<Message> currentMessages = OutputCollector.getAllMessages(); + int currentMessageIndex = currentMessages.size(); + if (lastMessageIndex < currentMessageIndex) { + for (int i = lastMessageIndex; i < currentMessageIndex; i++) { + messages.add(currentMessages.get(i)); + onMessage(currentMessages.get(i)); + } + lastMessageIndex = currentMessageIndex; + } + } + } + + public void finish() { + tlcRunning = false; + this.interrupt(); + } + + public abstract void onMessage(Message message); + + public List<Message> getMessages() { + return messages; + } +} diff --git a/src/main/java/de/tlc4b/tlc/TLCOutputInfo.java b/src/main/java/de/tlc4b/tlc/TLCOutputInfo.java index 8b9584664ec600025075019c221711ea5116260a..ed5a7bd500f44cc89c37fd010b25a63e8e70bfdd 100644 --- a/src/main/java/de/tlc4b/tlc/TLCOutputInfo.java +++ b/src/main/java/de/tlc4b/tlc/TLCOutputInfo.java @@ -15,11 +15,11 @@ import de.tlc4b.tla.TLAModule; public class TLCOutputInfo { - public Hashtable<String, String> namesMapping; - Hashtable<String, BType> typesTable; - Set<String> constants; + public final Hashtable<String, String> namesMapping; + final Hashtable<String, BType> typesTable; + final Set<String> constants; boolean constantSetup = false; - private boolean hasInit = false; + private final boolean hasInit; public boolean hasInitialisation() { return hasInit; @@ -42,22 +42,22 @@ public class TLCOutputInfo { } public boolean hasConstants() { - return constants.size() > 0 || constantSetup; + return !constants.isEmpty() || constantSetup; } public TLCOutputInfo(MachineContext machineContext, Renamer renamer, Typechecker typechecker, TLAModule tlaModule, ConfigFile configFile) { - this.namesMapping = new Hashtable<String, String>(); - this.typesTable = new Hashtable<String, BType>(); + this.namesMapping = new Hashtable<>(); + this.typesTable = new Hashtable<>(); this.constants = machineContext.getConstants().keySet(); - this.hasInit = tlaModule.getInitPredicates().size() > 0; + this.hasInit = !tlaModule.getInitPredicates().isEmpty(); if (machineContext.hasConstants()) { this.constantSetup = true; } - LinkedHashMap<String, Node> identifiers = new LinkedHashMap<String, Node>(); + LinkedHashMap<String, Node> identifiers = new LinkedHashMap<>(); identifiers.putAll(machineContext.getConstants()); identifiers.putAll(machineContext.getVariables()); identifiers.putAll(machineContext.getEnumValues()); diff --git a/src/main/java/de/tlc4b/tlc/TLCResults.java b/src/main/java/de/tlc4b/tlc/TLCResults.java index 7830582a7605c8778a9ad42b9301d3f418af78b0..8864a40ba9afeac78499c022c460ddfb27445208 100644 --- a/src/main/java/de/tlc4b/tlc/TLCResults.java +++ b/src/main/java/de/tlc4b/tlc/TLCResults.java @@ -1,58 +1,62 @@ package de.tlc4b.tlc; -import java.util.ArrayList; -import java.util.Date; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.Map.Entry; -import java.util.Set; - import de.tlc4b.TLC4BGlobals; import de.tlc4b.exceptions.NotSupportedException; -import static de.tlc4b.tlc.TLCResults.TLCResult.*; -import tla2sany.semantic.AssumeNode; -import tla2sany.semantic.ExprNode; -import tla2sany.semantic.ExprOrOpArgNode; -import tla2sany.semantic.ModuleNode; -import tla2sany.semantic.OpApplNode; -import tla2sany.semantic.OpDefNode; -import tla2sany.semantic.SymbolNode; -import tla2sany.semantic.ThmOrAssumpDefNode; +import tla2sany.semantic.*; import tla2sany.st.Location; import tlc2.output.EC; -import static tlc2.output.MP.*; +import tlc2.output.MP; import tlc2.output.Message; import tlc2.output.OutputCollector; import tlc2.tool.BuiltInOPs; +import tlc2.tool.TLCState; import tlc2.tool.TLCStateInfo; import tlc2.tool.ToolGlobals; +import java.util.*; +import java.util.Map.Entry; + +import static de.tlc4b.tlc.TLCResults.TLCResult.*; +import static tlc2.output.MP.*; + public class TLCResults implements ToolGlobals { private TLCResult tlcResult; - private String violatedDefinition; + private String violatedDefinition, tlcErrorMessage; private Date startTime; private Date endTime; - private LinkedHashMap<String, Long> operationsCount; - private ArrayList<String> violatedAssertions = new ArrayList<String>(); + private Map<String, Long> operationsCount; + private final List<String> violatedAssertions = new ArrayList<>(); private int lengthOfTrace; - private String traceString; + private String traceString, traceFile; private int numberOfDistinctStates; private int numberOfTransitions; - private TLCOutputInfo tlcOutputInfo; + private final TLCOutputInfo tlcOutputInfo; - public static enum TLCResult { - Deadlock, Goal, InvariantViolation, ParseError, NoError, AssertionError, PropertiesError, EnumerationError, TLCError, TemporalPropertyViolation, WellDefinednessError, InitialStateError; + public enum TLCResult { + Deadlock, Goal, InvariantViolation, ParseError, NoError, AssertionError, PropertiesError, EnumerationError, TLCError, TemporalPropertyViolation, WellDefinednessError, InitialStateError, Interrupted } public boolean hasTrace() { return lengthOfTrace > 0; } - public LinkedHashMap<String, Long> getOperationCount() { + public void addTraceFilePath(final String traceFile) { + this.traceFile = traceFile; + } + + public String getTraceFilePath() { + if (this.hasTrace() && this.traceFile != null) { + return this.traceFile; + } else { + return null; + } + } + + public Map<String, Long> getOperationCount() { return operationsCount; } @@ -73,59 +77,52 @@ public class TLCResults implements ToolGlobals { return violatedDefinition; } - public ArrayList<String> getViolatedAssertions(){ + public List<String> getViolatedAssertions() { return this.violatedAssertions; } - + public int getNumberOfTransitions() { return numberOfTransitions; } - public int getModelCheckingTime() { + public double getModelCheckingTime() { if (endTime == null || startTime == null) { return -1; } - return (int) (endTime.getTime() - startTime.getTime()) / 1000; + return (endTime.getTime() - startTime.getTime()) / 1000.0; } public void evalResults() { evalAllMessages(); - if (hasTrace() - || (TLC4BGlobals.getTestingMode() && OutputCollector - .getInitialState() != null)) { + if (hasTrace()) { evalTrace(); } - if (tlcResult == NoError && tlcOutputInfo.hasInitialisation() - && numberOfDistinctStates == 0) { + if (tlcResult == NoError && tlcOutputInfo.hasInitialisation() && numberOfDistinctStates == 0) { // Can not setup constants tlcResult = InitialStateError; } - if (TLC4BGlobals.isPrintCoverage() - && OutputCollector.getLineCountTable().size() != 0) { + if (TLC4BGlobals.isPrintCoverage() && !OutputCollector.getLineCountTable().isEmpty()) { evalCoverage(); } } private void evalCoverage() { - Hashtable<Integer, Long> lineCount = new Hashtable<Integer, Long>(); - Set<Entry<Location, Long>> entrySet = OutputCollector - .getLineCountTable().entrySet(); + Hashtable<Integer, Long> lineCount = new Hashtable<>(); + Set<Entry<Location, Long>> entrySet = OutputCollector.getLineCountTable().entrySet(); for (Entry<Location, Long> entry : entrySet) { int endline = entry.getKey().endLine(); if (lineCount.containsKey(endline)) { - lineCount.put(endline, - Math.max(lineCount.get(endline), entry.getValue())); + lineCount.put(endline, Math.max(lineCount.get(endline), entry.getValue())); } else { lineCount.put(endline, entry.getValue()); } } - ArrayList<OpDefNode> defs = getActionsFromGeneratedModule(OutputCollector - .getModuleNode()); - operationsCount = new LinkedHashMap<String, Long>(); + List<OpDefNode> defs = getActionsFromGeneratedModule(OutputCollector.getModuleNode()); + operationsCount = new LinkedHashMap<>(); for (OpDefNode opDefNode : defs) { String operationName = opDefNode.getName().toString(); Long count = lineCount.get(opDefNode.getLocation().endLine()); @@ -136,10 +133,9 @@ public class TLCResults implements ToolGlobals { } } - private ArrayList<OpDefNode> getActionsFromGeneratedModule( - ModuleNode moduleNode) { + private List<OpDefNode> getActionsFromGeneratedModule(ModuleNode moduleNode) { // list of actions in the module - ArrayList<OpDefNode> actions = new ArrayList<OpDefNode>(); + List<OpDefNode> actions = new ArrayList<>(); // get all definitions from the module OpDefNode[] opDefs = moduleNode.getOpDefs(); @@ -175,174 +171,179 @@ public class TLCResults implements ToolGlobals { if (opcode == OPCODE_be) { // BoundedExists return findAction(op1.getArgs()[0]); } else if (opNode instanceof OpDefNode) { - OpDefNode def = (OpDefNode) opNode; - return def; + return (OpDefNode) opNode; } else { throw new NotSupportedException( - "Can not find action in next state relation. Unkown node: " - + opNode.getClass()); - + "Can not find action in next state relation. Unknown node: " + opNode.getClass()); } } private void evalTrace() { - ArrayList<TLCStateInfo> trace = OutputCollector.getTrace(); - TracePrinter printer = null; - if (trace != null) { - printer = new TracePrinter(trace, tlcOutputInfo); - } else if (OutputCollector.getInitialState() != null) { - printer = new TracePrinter(OutputCollector.getInitialState(), - tlcOutputInfo); + List<TLCStateInfo> trace = OutputCollector.getTrace(); + TLCState initialState = OutputCollector.getInitialState(); + if (trace.isEmpty() && initialState != null) { + trace = Collections.singletonList(new TLCStateInfo(initialState)); } - if (printer != null) { + + if (!trace.isEmpty()) { + TracePrinter printer = new TracePrinter(trace, tlcOutputInfo); traceString = printer.getTrace().toString(); } } private void evalAllMessages() { - ArrayList<Message> messages = OutputCollector.getAllMessages(); + List<Message> messages = new ArrayList<>(OutputCollector.getAllMessages()); for (Message m : messages) { switch (m.getMessageClass()) { - case ERROR: - evalErrorMessage(m); - break; - case TLCBUG: - break; - case STATE: - lengthOfTrace++; - break; - case WARNING: - break; - case NONE: - evalStatusMessage(m); - break; - default: - break; + case ERROR: + evalErrorMessage(m); + if (tlcResult == null) { + tlcErrorMessage = MP.getError(m.getMessageCode(), m.getParameters()); + } + break; + case TLCBUG: + break; + case STATE: + lengthOfTrace++; + break; + case WARNING: + break; + case NONE: + evalStatusMessage(m); + break; + default: + break; } } - if (this.tlcResult == null) { - // this.tlcResult = TLCError; + if (this.tlcErrorMessage != null) { + this.tlcResult = TLCError; } - } private void evalStatusMessage(Message m) { switch (m.getMessageCode()) { - case EC.TLC_STARTING: - startTime = m.getDate(); - break; - case EC.TLC_FINISHED: - endTime = m.getDate(); - break; - - case EC.TLC_STATS: - numberOfTransitions = Integer.parseInt(m.getParameters()[0]); - numberOfDistinctStates = Integer.parseInt(m.getParameters()[1]); - break; - - case EC.TLC_STATS_DFID: + case EC.TLC_STARTING: + startTime = m.getDate(); + break; + case EC.TLC_FINISHED: + endTime = m.getDate(); + break; - break; + case EC.TLC_STATS: + case EC.TLC_STATS_DFID: + numberOfTransitions = Integer.parseInt(m.getParameters()[0]); + numberOfDistinctStates = Integer.parseInt(m.getParameters()[1]); + break; - case EC.TLC_SUCCESS: - tlcResult = TLCResult.NoError; - break; + case EC.TLC_SUCCESS: + tlcResult = TLCResult.NoError; + break; - default: - break; + default: + break; } } private void evalErrorMessage(Message m) { switch (m.getMessageCode()) { - case EC.TLC_INVARIANT_VIOLATED_INITIAL: - case EC.TLC_INVARIANT_VIOLATED_BEHAVIOR: - if (m.getParameters()[0].startsWith("Assertion")) { - tlcResult = AssertionError; - } else if (m.getParameters()[0].equals("NotGoal")) { - tlcResult = Goal; - } else if (m.getParameters()[0].startsWith("ASSERT_LTL")) { - tlcResult = TemporalPropertyViolation; - } else { - tlcResult = InvariantViolation; - } - if (m.getParameters().length > 0) { - violatedDefinition = m.getParameters()[0]; - } - break; + case EC.TLC_INVARIANT_VIOLATED_INITIAL: + case EC.TLC_INVARIANT_VIOLATED_BEHAVIOR: + if (m.getParameters()[0].startsWith("Assertion")) { + tlcResult = AssertionError; + } else if (m.getParameters()[0].equals("NotGoal")) { + tlcResult = Goal; + } else if (m.getParameters()[0].startsWith("ASSERT_LTL") || m.getParameters()[0].equals("ltl")) { + tlcResult = TemporalPropertyViolation; + } else { + tlcResult = InvariantViolation; + } + if (m.getParameters().length > 0) { + violatedDefinition = m.getParameters()[0]; + } + break; - case EC.TLC_INITIAL_STATE: { - String arg1 = m.getParameters()[0]; - if (arg1.contains("Attempted to compute the number of elements in the overridden")) { - // TODO + case EC.TLC_INITIAL_STATE: { + String arg1 = m.getParameters()[0]; + if (arg1.contains("Attempted to compute the number of elements in the overridden")) { + // TODO + } + tlcResult = EnumerationError; + return; } - tlcResult = EnumerationError; - return; - } - case EC.TLC_DEADLOCK_REACHED: - tlcResult = TLCResult.Deadlock; - break; - - case EC.TLC_ASSUMPTION_FALSE: - // get the violated assumption expr from the OutputCollector - ArrayList<ExprNode> violatedAssumptions = OutputCollector - .getViolatedAssumptions(); - if (violatedAssumptions.size() > 0) { - // try to find the assume node contain the expr in order to get - // the name of the assumption - for (ExprNode exprNode : violatedAssumptions) { - AssumeNode assumeNode = findAssumeNode(exprNode); - ThmOrAssumpDefNode def = assumeNode.getDef(); - // if the assumption is a named assumption, def is - // unequal null - // All B assertions are represented as named assumptions - // in the TLA module - if (def != null) { - String assertionName = def.getName().toString(); - if(!violatedAssertions.contains(assertionName)){ - this.violatedAssertions.add(assertionName); + case EC.TLC_DEADLOCK_REACHED: + tlcResult = TLCResult.Deadlock; + break; + + case EC.TLC_ASSUMPTION_FALSE: + // get the violated assumption expr from the OutputCollector + List<ExprNode> violatedAssumptions = OutputCollector.getViolatedAssumptions(); + if (!violatedAssumptions.isEmpty()) { + // try to find the assume node contain the expr in order to get + // the name of the assumption + for (ExprNode exprNode : violatedAssumptions) { + AssumeNode assumeNode = findAssumeNode(exprNode); + ThmOrAssumpDefNode def = assumeNode.getDef(); + // if the assumption is a named assumption, def is + // unequal null + // All B assertions are represented as named assumptions + // in the TLA module + if (def != null) { + String assertionName = def.getName().toString(); + if (!violatedAssertions.contains(assertionName)) { + this.violatedAssertions.add(assertionName); + } + tlcResult = TLCResult.AssertionError; } - tlcResult = TLCResult.AssertionError; - } + } } - } - if(tlcResult == null){ - // otherwise, it is normal properties error - tlcResult = TLCResult.PropertiesError; - } - break; + if (tlcResult == null) { + // otherwise, it is normal properties error + tlcResult = TLCResult.PropertiesError; + } + break; - case EC.TLC_TEMPORAL_PROPERTY_VIOLATED: - tlcResult = TLCResult.TemporalPropertyViolation; - if (m.getParameters().length > 0) { - violatedDefinition = m.getParameters()[0]; - } - break; + case EC.TLC_TEMPORAL_PROPERTY_VIOLATED: + tlcResult = TLCResult.TemporalPropertyViolation; + if (m.getParameters().length > 0) { + violatedDefinition = m.getParameters()[0]; + } + break; - case EC.TLC_ASSUMPTION_EVALUATION_ERROR: - tlcResult = evaluatingParameter(m.getParameters()); - break; + case EC.TLC_VALUE_ASSERT_FAILED: + tlcResult = WellDefinednessError; + break; - case EC.TLC_VALUE_ASSERT_FAILED: - tlcResult = WellDefinednessError; - break; + case EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE: + if (m.getParameters()[0].contains("tlc2.module.TLC.Assert")) { + tlcResult = WellDefinednessError; + } + break; - case EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE: - if (m.getParameters()[0].contains("tlc2.module.TLC.Assert")) { - tlcResult = WellDefinednessError; - } - break; + case EC.TLC_CONFIG_ID_HAS_VALUE: // LTL errors, Assertion violations + String kind = m.getParameters()[0]; + String id = m.getParameters()[1]; + // third param should be "FALSE" (we are already in error case here) + if (kind.contains("property") && id.startsWith("ASSERT_LTL")) { + tlcResult = TemporalPropertyViolation; + } else if (kind.contains("invariant") && id.startsWith("Assertion")) { + tlcResult = AssertionError; + } else { + // just as fall-back + tlcResult = evaluatingParameter(m.getParameters()); + } + break; - case EC.GENERAL: - tlcResult = evaluatingParameter(m.getParameters()); - break; + case EC.TLC_ASSUMPTION_EVALUATION_ERROR: + case EC.GENERAL: + tlcResult = evaluatingParameter(m.getParameters()); + break; } } @@ -358,8 +359,7 @@ public class TLCResults implements ToolGlobals { } private TLCResult evaluatingParameter(String[] params) { - for (int i = 0; i < params.length; i++) { - String s = params[i]; + for (String s : params) { if (s == null) { break; } else if (s.contains("not enumerable")) { @@ -368,22 +368,24 @@ public class TLCResults implements ToolGlobals { return AssertionError; } else if (s.contains("The invariant of Invariant")) { return InvariantViolation; - } else if (s.contains("In applying the function")) { - return WellDefinednessError; - } else if (s.contains("which is not in the domain of the function")) { + } else if (s.contains("In applying the function") + || s.contains("which is not in the domain of the function") + || s.contains("tlc2.module.TLC.Assert") + || (s.contains("CHOOSE x \\in S: P, but no element of S satisfied P") && s.contains("module FunctionsAsRelations")) + // messages from BBuiltIns: + || s.contains("Both operands of the modulo operator must be natural numbers") + || s.contains("Division by zero") + || s.contains("Applied the inter operator to an empty set") + || s.replace("\n","").matches(".*The.*argument.*operator should be.*sequence.*") + || s.replace("\n","").matches(".*The.*argument.*operator is an invalid number.*")) { return WellDefinednessError; - } else if (s.contains("tlc2.module.TLC.Assert")) { - return WellDefinednessError; - } else if (s - .contains("CHOOSE x \\in S: P, but no element of S satisfied P") - && s.contains("module FunctionsAsRelations")) { - return tlcResult = WellDefinednessError; - } else if (s.contains("The property of ASSERT_LTL")) { + } else if (s.contains("ASSERT_LTL")) { return TemporalPropertyViolation; + } else if (s.contains("java.lang.InterruptedException")) { + return Interrupted; } - } - // unkown error + // unknown error return null; } @@ -391,6 +393,10 @@ public class TLCResults implements ToolGlobals { return tlcResult; } + public String getTLCErrorMessage() { + return tlcErrorMessage; + } + public String getResultString() { if (tlcResult == TLCResult.InvariantViolation) { return "Invariant Violation"; diff --git a/src/main/java/de/tlc4b/tlc/TracePrinter.java b/src/main/java/de/tlc4b/tlc/TracePrinter.java index a03c9a34f3111734c0b8277e924392f5f1a61a5a..6e5fd3eb22f8e87fe234dd31ac78ec7c84c8e848 100644 --- a/src/main/java/de/tlc4b/tlc/TracePrinter.java +++ b/src/main/java/de/tlc4b/tlc/TracePrinter.java @@ -1,6 +1,7 @@ package de.tlc4b.tlc; import java.util.ArrayList; +import java.util.List; import de.tlc4b.btypes.BType; import de.tlc4b.btypes.FunctionType; @@ -11,52 +12,27 @@ import de.tlc4b.exceptions.NotSupportedException; import tla2sany.semantic.OpDeclNode; import tlc2.tool.TLCState; import tlc2.tool.TLCStateInfo; -import tlc2.value.FcnLambdaValue; -import tlc2.value.FcnRcdValue; -import tlc2.value.IntervalValue; -import tlc2.value.LazyValue; -import tlc2.value.ModelValue; -import tlc2.value.RecordValue; -import tlc2.value.SetCapValue; -import tlc2.value.SetCupValue; -import tlc2.value.SetDiffValue; -import tlc2.value.SetEnumValue; -import tlc2.value.SetOfFcnsValue; -import tlc2.value.SetOfRcdsValue; -import tlc2.value.SetOfTuplesValue; -import tlc2.value.SetPredValue; -import tlc2.value.StringValue; -import tlc2.value.SubsetValue; -import tlc2.value.TupleValue; -import tlc2.value.UnionValue; -import tlc2.value.Value; -import tlc2.value.ValueEnumeration; -import tlc2.value.ValueVec; +import tlc2.value.impl.*; import util.UniqueString; import static tlc2.value.ValueConstants.*; public class TracePrinter { - ArrayList<TLCStateInfo> trace; + List<TLCStateInfo> trace; TLCState initialState; - TLCOutputInfo tlcOutputInfo; + final TLCOutputInfo tlcOutputInfo; - ArrayList<OpDeclNode> constants; - ArrayList<OpDeclNode> variables; + List<OpDeclNode> constants; + List<OpDeclNode> variables; StringBuilder traceBuilder; - public TracePrinter(ArrayList<TLCStateInfo> trace, - TLCOutputInfo tlcOutputInfo) { + public TracePrinter(List<TLCStateInfo> trace, TLCOutputInfo tlcOutputInfo) { this.trace = trace; this.tlcOutputInfo = tlcOutputInfo; - setup(); - } - - private void setup() { - constants = new ArrayList<OpDeclNode>(); - variables = new ArrayList<OpDeclNode>(); + constants = new ArrayList<>(); + variables = new ArrayList<>(); for (int i = 0; i < TLCState.vars.length; i++) { String tlaName = TLCState.vars[i].getName().toString(); String bName = tlcOutputInfo.getBName(tlaName); @@ -69,12 +45,6 @@ public class TracePrinter { evalTrace(); } - public TracePrinter(TLCState initialState, TLCOutputInfo tlcOutputInfo) { - this.initialState = initialState; - this.tlcOutputInfo = tlcOutputInfo; - setup(); - } - public StringBuilder getTrace() { return traceBuilder; } @@ -101,7 +71,7 @@ public class TracePrinter { private StringBuilder setupConstants(TLCState state) { StringBuilder expression = new StringBuilder(); if (tlcOutputInfo.constantSetup) { - if (constants.size() == 0) { + if (constants.isEmpty()) { expression.append("1 = 1"); } else { for (int i = 0; i < constants.size(); i++) { @@ -111,8 +81,7 @@ public class TracePrinter { UniqueString var = constants.get(i).getName(); String bName = tlcOutputInfo.getBName(var.toString()); BType type = tlcOutputInfo.getBType(var.toString()); - String value = parseValue(state.lookup(var), type) - .toString(); + String value = parseValue((Value) state.lookup(var), type).toString(); expression.append(bName).append(" = ").append(value); } } @@ -131,7 +100,7 @@ public class TracePrinter { UniqueString var = variables.get(i).getName(); String bName = tlcOutputInfo.getBName(var.toString()); BType type = tlcOutputInfo.getBType(var.toString()); - String value = parseValue(state.lookup(var), type).toString(); + String value = parseValue((Value) state.lookup(var), type).toString(); expression.append(bName).append(" = ").append(value); } return expression; @@ -175,18 +144,17 @@ public class TracePrinter { } else if (type instanceof FunctionType) { if (((TupleValue) val).elems.length == 0) { res.append("{}"); - return res; } else { BType subtype = ((FunctionType) type).getRange(); res.append("["); res.append(parseEnumerationValue(((TupleValue) val).elems, subtype)); res.append("]"); - return res; } + return res; } - throw new NotSupportedException("Unkown type of tuple."); + throw new NotSupportedException("Unknown type of tuple."); case RECORDVALUE: { RecordValue rec = (RecordValue) val; @@ -319,7 +287,7 @@ public class TracePrinter { case LAZYVALUE: { LazyValue s = (LazyValue) val; - res.append(parseValue(s.val, type)); + res.append(parseValue(s.getValue(), type)); return res; } diff --git a/src/main/java/de/tlc4b/util/StopWatch.java b/src/main/java/de/tlc4b/util/StopWatch.java index 7ef4d84a568764b2b85c50979eeb05134b040d44..9ad5948671d0077ad55c07e7ae44b7516e77e102 100644 --- a/src/main/java/de/tlc4b/util/StopWatch.java +++ b/src/main/java/de/tlc4b/util/StopWatch.java @@ -5,8 +5,8 @@ import java.util.Hashtable; public class StopWatch { - private static final Hashtable<Watches, Long> startTime = new Hashtable<Watches, Long>(); - private static final Hashtable<Watches, Long> runTime = new Hashtable<Watches, Long>(); + private static final Hashtable<Watches, Long> startTime = new Hashtable<>(); + private static final Hashtable<Watches, Long> runTime = new Hashtable<>(); public enum Watches{ PARSING_TIME, TRANSLATION_TIME, TLC_TIME, OVERALL_TIME, MODEL_CHECKING_TIME @@ -17,8 +17,7 @@ public class StopWatch { } public static long stop(Watches id) { - long stopTime = System.currentTimeMillis() - - startTime.remove(id); + long stopTime = System.currentTimeMillis() - startTime.remove(id); runTime.put(id, stopTime); return stopTime; } diff --git a/src/main/java/de/tlc4b/util/UtilMethods.java b/src/main/java/de/tlc4b/util/UtilMethods.java index 3ff3fe47a0e76de4f44e28eb099c2e1389fb03a5..2e824b3dfc82c032a7c063d09142440a9e3d82c2 100644 --- a/src/main/java/de/tlc4b/util/UtilMethods.java +++ b/src/main/java/de/tlc4b/util/UtilMethods.java @@ -2,19 +2,40 @@ package de.tlc4b.util; import java.util.ArrayList; -import de.be4.classicalb.core.parser.node.AIdentifierExpression; -import de.be4.classicalb.core.parser.node.Node; -import de.be4.classicalb.core.parser.node.TIdentifierLiteral; +import de.be4.classicalb.core.parser.node.*; import de.hhu.stups.sablecc.patch.SourcePosition; public class UtilMethods { public static AIdentifierExpression createAIdentifierExpression(String name) { TIdentifierLiteral literal = new TIdentifierLiteral(name); - ArrayList<TIdentifierLiteral> idList = new ArrayList<TIdentifierLiteral>(); + ArrayList<TIdentifierLiteral> idList = new ArrayList<>(); idList.add(literal); - AIdentifierExpression id = new AIdentifierExpression(idList); - return id; + return new AIdentifierExpression(idList); + } + + public static AIdentifierExpression getIdentifierExpression(PExpression e) { + AIdentifierExpression identifier; + if (e instanceof ADescriptionExpression) { + identifier = getIdentifierExpression(((ADescriptionExpression) e).getExpression()); + } else if (e instanceof AIdentifierExpression) { + identifier = (AIdentifierExpression) e; + } else { + throw new IllegalStateException("Unexpected expression type: " + e); + } + return identifier; + } + + public static AOperation getOperation(POperation e) { + AOperation op; + if (e instanceof ADescriptionOperation) { + op = getOperation(((ADescriptionOperation) e).getOperation()); + } else if (e instanceof AOperation) { + op = (AOperation) e; + } else { + throw new IllegalStateException("Unexpected operation type: " + e); + } + return op; } public static String getPositionAsString(Node node) { diff --git a/src/main/resources/standardModules/BBuiltIns.tla b/src/main/resources/de/tlc4b/standardModules/BBuiltIns.tla similarity index 100% rename from src/main/resources/standardModules/BBuiltIns.tla rename to src/main/resources/de/tlc4b/standardModules/BBuiltIns.tla diff --git a/src/main/resources/standardModules/ExternalFunctions.tla b/src/main/resources/de/tlc4b/standardModules/ExternalFunctions.tla similarity index 100% rename from src/main/resources/standardModules/ExternalFunctions.tla rename to src/main/resources/de/tlc4b/standardModules/ExternalFunctions.tla diff --git a/src/main/resources/standardModules/Functions.tla b/src/main/resources/de/tlc4b/standardModules/Functions.tla similarity index 100% rename from src/main/resources/standardModules/Functions.tla rename to src/main/resources/de/tlc4b/standardModules/Functions.tla diff --git a/src/main/resources/standardModules/FunctionsAsRelations.tla b/src/main/resources/de/tlc4b/standardModules/FunctionsAsRelations.tla similarity index 100% rename from src/main/resources/standardModules/FunctionsAsRelations.tla rename to src/main/resources/de/tlc4b/standardModules/FunctionsAsRelations.tla diff --git a/src/main/resources/standardModules/Relations.tla b/src/main/resources/de/tlc4b/standardModules/Relations.tla similarity index 100% rename from src/main/resources/standardModules/Relations.tla rename to src/main/resources/de/tlc4b/standardModules/Relations.tla diff --git a/src/main/resources/standardModules/SequencesAsRelations.tla b/src/main/resources/de/tlc4b/standardModules/SequencesAsRelations.tla similarity index 99% rename from src/main/resources/standardModules/SequencesAsRelations.tla rename to src/main/resources/de/tlc4b/standardModules/SequencesAsRelations.tla index a7eed1310b6196f7dffce420f1c607af7e4bb9fa..a8b92ffc89d07880e0c933faa520b3d98d289d51 100644 --- a/src/main/resources/standardModules/SequencesAsRelations.tla +++ b/src/main/resources/de/tlc4b/standardModules/SequencesAsRelations.tla @@ -70,7 +70,7 @@ RelSeqConcat(s1, s2) == WDcheck(s1 \cup {<<x[1]+Cardinality(s1), x[2]>> : x \in s2} , SeqTest(s1) /\ SeqTest(s2), "Error: The arguments of the concatenation-operator should be sequences.") \* The concatenation of sequence s1 and sequence s2 -RelSeqPrepand(e, s) == +RelSeqPrepend(e, s) == IF Assert(SeqTest(s), "Error: The second argument of the prepend-operator should be a sequence.") THEN {<<1,e>>} \cup {<<x[1]+1, x[2]>> : x \in s} ELSE {} \* dummy diff --git a/src/main/resources/standardModules/SequencesExtended.tla b/src/main/resources/de/tlc4b/standardModules/SequencesExtended.tla similarity index 100% rename from src/main/resources/standardModules/SequencesExtended.tla rename to src/main/resources/de/tlc4b/standardModules/SequencesExtended.tla diff --git a/src/test/java/de/tlc4b/analysis/ConstantsTest.java b/src/test/java/de/tlc4b/analysis/ConstantsTest.java index ccd9b9cd60b9d3493400590188e2937e7714aeb2..fc42e4d2d88e8a69a8b32fe067820f67407884fd 100644 --- a/src/test/java/de/tlc4b/analysis/ConstantsTest.java +++ b/src/test/java/de/tlc4b/analysis/ConstantsTest.java @@ -38,7 +38,7 @@ public class ConstantsTest { } @Test - public void testConstantMultiplePossipleValues() throws Exception { + public void testConstantMultiplePossibleValues() throws Exception { String machine = "MACHINE test\n" + "CONSTANTS k \n" + "PROPERTIES k : {1} \n" + "END"; @@ -134,5 +134,18 @@ public class ConstantsTest { + "======"; compare(expected, machine); } + + @Test + public void testConstantsDescPragma() throws Exception { + String machine = "MACHINE test\n" + + "CONSTANTS n /*@desc description*/\n" + + "PROPERTIES n = 1\n" + + "END"; + + String expected = "---- MODULE test----\n" + + "n == 1\n" + + "======"; + compare(expected, machine); + } } diff --git a/src/test/java/de/tlc4b/analysis/DeferredSetSizeTest.java b/src/test/java/de/tlc4b/analysis/DeferredSetSizeTest.java index ebd3193d910182cd768a353f6ae844507e5182fa..9ebb7d750c4cd4ca5f8ad793c002ae4cc98017f5 100644 --- a/src/test/java/de/tlc4b/analysis/DeferredSetSizeTest.java +++ b/src/test/java/de/tlc4b/analysis/DeferredSetSizeTest.java @@ -10,10 +10,10 @@ public class DeferredSetSizeTest { String machine = "MACHINE test\n" + "SETS S \n" + "END"; - String expectedModule = "---- MODULE test----\n" + String expectedModule = "---- MODULE test ----\n" + "CONSTANTS S\n" - + "======"; - String expectedConfig = "CONSTANTS S = {S1, S2, S3} "; + + "===="; + String expectedConfig = "CONSTANTS\nS = {S1,S2,S3}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -23,12 +23,12 @@ public class DeferredSetSizeTest { + "SETS S \n" + "PROPERTIES card(S) = 4" + "END"; - String expectedModule = "---- MODULE test----\n" - + "EXTENDS FiniteSets \n" + String expectedModule = "---- MODULE test ----\n" + + "EXTENDS FiniteSets\n" + "CONSTANTS S\n" - + "ASSUME Cardinality(S) = 4 \n" - + "======"; - String expectedConfig = "CONSTANTS S = {S1, S2, S3, S4} "; + + "ASSUME Cardinality(S) = 4\n" + + "===="; + String expectedConfig = "CONSTANTS\nS = {S1,S2,S3,S4}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -38,12 +38,12 @@ public class DeferredSetSizeTest { + "SETS S \n" + "PROPERTIES 4 = card(S)" + "END"; - String expectedModule = "---- MODULE test----\n" - + "EXTENDS FiniteSets \n" + String expectedModule = "---- MODULE test ----\n" + + "EXTENDS FiniteSets\n" + "CONSTANTS S\n" - + "ASSUME 4 = Cardinality(S) \n" - + "======"; - String expectedConfig = "CONSTANTS S = {S1, S2, S3, S4} "; + + "ASSUME 4 = Cardinality(S)\n" + + "===="; + String expectedConfig = "CONSTANTS\nS = {S1,S2,S3,S4}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } } diff --git a/src/test/java/de/tlc4b/analysis/RenamerTest.java b/src/test/java/de/tlc4b/analysis/RenamerTest.java index 4150660b493346827c938976e0dd5f3606147fb7..9a6bd6dc08f2840ca2357c4d94c86c66b5c7fa39 100644 --- a/src/test/java/de/tlc4b/analysis/RenamerTest.java +++ b/src/test/java/de/tlc4b/analysis/RenamerTest.java @@ -1,9 +1,10 @@ package de.tlc4b.analysis; -import static de.tlc4b.util.TestUtil.*; - import org.junit.Test; +import static de.tlc4b.util.TestUtil.*; +import static org.junit.Assert.assertEquals; + public class RenamerTest { @@ -104,7 +105,7 @@ public class RenamerTest { + "S == {aa}\n" + "ASSUME \\E aa_1 \\in {1} : TRUE\n" + "===="; - compareEquals(expected, machine); + assertEquals(expected, translate(machine)); } } diff --git a/src/test/java/de/tlc4b/analysis/ScopeTest.java b/src/test/java/de/tlc4b/analysis/ScopeTest.java index 6c8802a4c230b80cf60f3fc4abc86181cb92c23d..96b5355a58965a0361be717c97304203fab3dcd3 100644 --- a/src/test/java/de/tlc4b/analysis/ScopeTest.java +++ b/src/test/java/de/tlc4b/analysis/ScopeTest.java @@ -112,7 +112,7 @@ public class ScopeTest { } @Test(expected = ScopeException.class) - public void testUnkownOperation() throws Exception { + public void testUnknownOperation() throws Exception { String machine = "MACHINE test\n" + "INITIALISATION foo \n" + "END"; checkMachine(machine); } diff --git a/src/test/java/de/tlc4b/analysis/UnsupportedConstructsTest.java b/src/test/java/de/tlc4b/analysis/UnsupportedConstructsTest.java index 030e63909a46c54e6661022ad9f6b0412c82bd9d..84696b21d10fc3e7cbf6d1ae91ae9773f5272621 100644 --- a/src/test/java/de/tlc4b/analysis/UnsupportedConstructsTest.java +++ b/src/test/java/de/tlc4b/analysis/UnsupportedConstructsTest.java @@ -11,12 +11,12 @@ public class UnsupportedConstructsTest { @Test(expected = NotSupportedException.class) public void testExtends() throws Exception { final String machine = "MACHINE test\n" + "EXTENDS foo\n PROMOTES bar\n" + "END"; - tryTranslating(machine); + translate(machine); } @Test(expected = NotSupportedException.class) public void testImplementation() throws Exception { final String machine = "IMPLEMENTATION test REFINES foo END"; - tryTranslating(machine); + translate(machine); } } diff --git a/src/test/java/de/tlc4b/ltl/LTLFormulaTest.java b/src/test/java/de/tlc4b/ltl/LTLFormulaTest.java index 8e4ead8e8d8ce6ff24aafb03f723f86f6a9b72e2..70a4f5ef25e4240c736a63cb6d71d23f967fccf5 100644 --- a/src/test/java/de/tlc4b/ltl/LTLFormulaTest.java +++ b/src/test/java/de/tlc4b/ltl/LTLFormulaTest.java @@ -1,26 +1,16 @@ package de.tlc4b.ltl; - -import static de.tlc4b.util.TestUtil.compareEqualsConfig; -import static de.tlc4b.util.TestUtil.compareLTLFormula; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import de.tlc4b.TLC4BGlobals; import de.tlc4b.exceptions.LTLParseException; import de.tlc4b.exceptions.ScopeException; import de.tlc4b.exceptions.TypeErrorException; +import org.junit.Ignore; +import org.junit.Test; -public class LTLFormulaTest { +import static de.tlc4b.util.TestUtil.compareLTLFormula; +import static de.tlc4b.util.TestUtil.compareModuleAndConfig; - @BeforeClass - public static void setUp(){ - TLC4BGlobals.setTestingMode(true); - } - +public class LTLFormulaTest { @Test (expected = ScopeException.class) public void testScopeException() throws Exception { String machine = "MACHINE test\n" @@ -59,7 +49,7 @@ public class LTLFormulaTest { @Test public void testFinally() throws Exception { String machine = "MACHINE test END"; - compareLTLFormula("<>(1=1)", machine, "F{1 = 1}"); + compareLTLFormula("<>(1 = 1)", machine, "F{1 = 1}"); } @Test @@ -222,7 +212,7 @@ public class LTLFormulaTest { + "INITIALISATION x := 1\n" + "OPERATIONS foo = skip\n" + "END"; - String expected = "([]<><<foo>>_vars\\/[]<>~ENABLED(foo)\\/[]<>ENABLED(foo/\\x'=x))=>TRUE"; + String expected = "([]<><<foo>>_vars \\/ []<>~ENABLED(foo) \\/ []<>ENABLED(foo /\\ x' = x)) => TRUE"; compareLTLFormula(expected, machine, "WF(foo) => true"); } @@ -234,14 +224,14 @@ public class LTLFormulaTest { + "INITIALISATION x := 1\n" + "OPERATIONS foo = x := 1" + "END"; - String expected = "([]<><<foo>>_vars\\/<>[]~ENABLED(foo)\\/[]<>ENABLED(foo/\\x'=x))=>TRUE"; + String expected = "([]<><<foo>>_vars \\/ <>[]~ENABLED(foo) \\/ []<>ENABLED(foo /\\ x' = x)) => TRUE"; compareLTLFormula(expected, machine, "SF(foo) => true"); } @Test public void testExistentialQuantification() throws Exception { String machine = "MACHINE test END"; - compareLTLFormula(" \\E p \\in {1}: p = 1", machine, "#p.({p=1} & {p = 1})"); + compareLTLFormula("\\E p \\in {1}: p = 1", machine, "#p.({p=1} & {p = 1})"); } @Test @@ -284,7 +274,7 @@ public class LTLFormulaTest { + "===="; final String config = "SPECIFICATION Spec\nINVARIANT Invariant\nPROPERTIES ASSERT_LTL\n"; - compareEqualsConfig(expected, config, machine); + compareModuleAndConfig(expected, config, machine); } } diff --git a/src/test/java/de/tlc4b/prettyprint/EnumeratedSetsTest.java b/src/test/java/de/tlc4b/prettyprint/EnumeratedSetsTest.java index f610ead1fccd087b10f4b04e8edf232755d8222d..5164f1b7d17a2d86d73442f1d69564cc0f1156c3 100644 --- a/src/test/java/de/tlc4b/prettyprint/EnumeratedSetsTest.java +++ b/src/test/java/de/tlc4b/prettyprint/EnumeratedSetsTest.java @@ -17,6 +17,6 @@ public class EnumeratedSetsTest { + "set2 == {d}\n" + "===="; final String config = "CONSTANTS\na = a\nb = b\nc = c\nd = d\n"; - compareEqualsConfig(expected, config, machine); + compareModuleAndConfig(expected, config, machine); } } diff --git a/src/test/java/de/tlc4b/prettyprint/FunctionTest.java b/src/test/java/de/tlc4b/prettyprint/FunctionTest.java index f191f7bb19c380a3b33cb287b64628c2801a7c88..f02da43887f4eccdd8ca624e97314f9bb8cf78d1 100644 --- a/src/test/java/de/tlc4b/prettyprint/FunctionTest.java +++ b/src/test/java/de/tlc4b/prettyprint/FunctionTest.java @@ -1,10 +1,9 @@ package de.tlc4b.prettyprint; -import static de.tlc4b.util.TestUtil.*; - import org.junit.Test; - +import static de.tlc4b.util.TestUtil.*; +import static org.junit.Assert.assertEquals; public class FunctionTest { @@ -97,7 +96,7 @@ public class FunctionTest { String expected = "---- MODULE test ----\n" + "ASSUME [{1} -> {1}] = [{1} -> {1}]\n" + "===="; - compareEquals(expected, machine); + assertEquals(expected, translate(machine)); } @@ -109,7 +108,7 @@ public class FunctionTest { + "EXTENDS Functions\n" + "ASSUME {} = ParFunc({1, 2}, {1, 2})\n" + "===="; - compareEquals(expected, machine); + assertEquals(expected, translate(machine)); } } diff --git a/src/test/java/de/tlc4b/prettyprint/MachineParameterTest.java b/src/test/java/de/tlc4b/prettyprint/MachineParameterTest.java index 2ee04a8252b9371af16bb1eefc7bcc9580acb020..e6123946cee8bd4ca9b8eb8744fa9901ae3263d3 100644 --- a/src/test/java/de/tlc4b/prettyprint/MachineParameterTest.java +++ b/src/test/java/de/tlc4b/prettyprint/MachineParameterTest.java @@ -24,12 +24,13 @@ public class MachineParameterTest { + "CONSTRAINTS a : {1,2,3}\n" + "END"; - String expectedModule = "---- MODULE test----\n" + String expectedModule = "---- MODULE test ----\n" + "VARIABLES a\n" - + "Init == a \\in {1,2,3}\n" + + "Init == a \\in {1, 2, 3}\n" + + "\n" + "Next == 1 = 2 /\\ UNCHANGED <<a>>\n" - + "======"; - String expectedConfig = "INIT Init\nNEXT Next"; + + "===="; + String expectedConfig = "INIT Init\nNEXT Next\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -51,10 +52,10 @@ public class MachineParameterTest { String machine = "MACHINE test(AA)\n" + "END"; - String expectedModule = "---- MODULE test----\n" + String expectedModule = "---- MODULE test ----\n" + "CONSTANTS AA\n" - + "======"; - String expectedConfig = "CONSTANTS AA = {AA1, AA2, AA3}"; + + "===="; + String expectedConfig = "CONSTANTS\nAA = {AA1,AA2,AA3}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -69,7 +70,7 @@ public class MachineParameterTest { + "a == 1\n" + "ASSUME Cardinality(B) = 2\n" + "===="; - String expectedConfig = "CONSTANTS B = {B1, B2, B3}"; + String expectedConfig = "CONSTANTS\nB = {B1,B2,B3}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } diff --git a/src/test/java/de/tlc4b/prettyprint/OperationsTest.java b/src/test/java/de/tlc4b/prettyprint/OperationsTest.java index ceafde9351a7f4a24630ca1797772793a840af86..1741ed12ab89d41915f1e5f45f3c31da107b9f36 100644 --- a/src/test/java/de/tlc4b/prettyprint/OperationsTest.java +++ b/src/test/java/de/tlc4b/prettyprint/OperationsTest.java @@ -405,5 +405,26 @@ public class OperationsTest { + "===="; compare(expected, machine); } + + @Test + public void testOperationWithDescPragma() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x\n" + + "INVARIANT x = 1\n" + + "INITIALISATION x := 1\n" + + "OPERATIONS\n" + + "inc = x := x + 1 /*@desc increment x*/\n" + + "END"; + + String expected = "---- MODULE test ----\n" + + "EXTENDS Naturals\n" + + "VARIABLES x \n" + + "Invariant1 == x = 1\n" + + "Init == x = 1 \n" + + "inc == x' = x + 1\n" + + "Next == \\/ inc \n" + + "===="; + compare(expected, machine); + } } diff --git a/src/test/java/de/tlc4b/prettyprint/SetTest.java b/src/test/java/de/tlc4b/prettyprint/SetTest.java index 8e66fcbcffe6ea34316fdaccc832551c2cbc4a09..f08a95b6bbbe52d0d9e3e5bf58bace2cd678df98 100644 --- a/src/test/java/de/tlc4b/prettyprint/SetTest.java +++ b/src/test/java/de/tlc4b/prettyprint/SetTest.java @@ -190,7 +190,7 @@ public class SetTest { + "ASSUME UNION({{z}: z \\in {z \\in ({1, 2}): 1 = 1}}) = {1, 2}\n" + "===="; //TODO ERROR in TLA2B - compareEquals(expected, machine); + assertEquals(expected, translate(machine)); } @Test @@ -201,7 +201,7 @@ public class SetTest { + "EXTENDS BBuiltIns\n" + "ASSUME Inter({{z}: z \\in {z \\in ({1, 2}): 1 = 1}}) = {}\n" + "===="; - compareEquals(expected, machine); + assertEquals(expected, translate(machine)); } } diff --git a/src/test/java/de/tlc4b/prettyprint/SetsClauseTest.java b/src/test/java/de/tlc4b/prettyprint/SetsClauseTest.java index 2d12db49152344912eb7f14fbd4edd2d8011fe23..ca6f87fcecb24523e763b636ba0ee235c9f4abfc 100644 --- a/src/test/java/de/tlc4b/prettyprint/SetsClauseTest.java +++ b/src/test/java/de/tlc4b/prettyprint/SetsClauseTest.java @@ -10,11 +10,11 @@ public class SetsClauseTest { String machine = "MACHINE test\n" + "SETS d \n" + "END"; - String expectedModule = "---- MODULE test----\n" + String expectedModule = "---- MODULE test ----\n" + "CONSTANTS d\n" - + "======"; + + "===="; String expectedConfig = "CONSTANTS\n" + - "d = {d1, d2, d3}\n"; + "d = {d1,d2,d3}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -26,11 +26,17 @@ public class SetsClauseTest { + "CONSTANTS k \n" + "PROPERTIES k : d \n" + "END"; - String expectedModule = "---- MODULE test----\n" - + "CONSTANTS d2asisdfapsdjfa\n" - + "======"; - String expectedConfig = "CONSTANTS\n" + - "d = {d1, d2, d3}\n"; + String expectedModule = "---- MODULE test ----\n" + + "CONSTANTS d\n" + + "VARIABLES k\n" + + "Init == k \\in d\n" + + "\n" + + "Next == 1 = 2 /\\ UNCHANGED <<k>>\n" + + "===="; + String expectedConfig = "INIT Init\n" + + "NEXT Next\n" + + "CONSTANTS\n" + + "d = {d1,d2,d3}\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } @@ -40,11 +46,11 @@ public class SetsClauseTest { String machine = "MACHINE test\n" + "SETS S = {a,b,c} \n" + "END"; - String expectedModule = "---- MODULE test----\n" + String expectedModule = "---- MODULE test ----\n" + "CONSTANTS a, b, c\n" - + "S == {a, b, c}" - + "======"; - String expectedConfig = "CONSTANTS a = a\n b = b \n c = c"; + + "S == {a, b, c}\n" + + "===="; + String expectedConfig = "CONSTANTS\na = a\nb = b\nc = c\n"; compareModuleAndConfig(expectedModule, expectedConfig, machine); } } diff --git a/src/test/java/de/tlc4b/prettyprint/SubstitutionsTest.java b/src/test/java/de/tlc4b/prettyprint/SubstitutionsTest.java index 3965d7d575b53aff3ae73d8e891f9b4ff9e27c55..8f67b211049a13e011566b9e6f90847c82fa7e9a 100644 --- a/src/test/java/de/tlc4b/prettyprint/SubstitutionsTest.java +++ b/src/test/java/de/tlc4b/prettyprint/SubstitutionsTest.java @@ -17,13 +17,180 @@ public class SubstitutionsTest { compare(null, machine); } - @Test (expected = SubstitutionException.class) + @Test (expected = SubstitutionException.class) public void testMissingVariableAssignment() throws Exception { String machine = "MACHINE test\n" + "VARIABLES x,y \n" + "INVARIANT x = 1 & y = 1 \n" + "INITIALISATION x := 1 \n" + "END"; compare(null, machine); } + + @Test + public void testAssignSequentialSubstitutionSimple() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x,y\n" + + "INVARIANT x = 1 & y = 3 \n" + + "INITIALISATION x := 1 ; y := x \n" + + "OPERATIONS\n" + + " op1 = BEGIN x := 1 ; y := x + 1 END; \n" + + " op2 = BEGIN x := 1 || y := x + 1 END; \n" + + " op3 = BEGIN x := y ; y := 1 END; \n" + + " op4 = BEGIN x := y || y := 1 END; \n" + + " op5 = BEGIN x, y := x + 1, x + 1 END \n" + + "END"; + + String expected = "---- MODULE test ----\n" + + "EXTENDS Naturals\n" + + "VARIABLES x, y\n" + + "Invariant1 == x = 1\n" + + "Invariant2 == y = 3\n" + + "Init == x = 1 /\\ y = x\n" + + "\n" + + "op1 == x' = 1 /\\ y' = x' + 1\n" + + "\n" + + "op2 == x' = 1 /\\ y' = x + 1\n" + + "\n" + + "op3 == x' = y /\\ y' = 1\n" + + "\n" + + "op4 == x' = y /\\ y' = 1\n" + + "\n" + + "op5 == x' = x + 1 /\\ y' = x + 1\n" + + "\n" + + "Next == \\/ op1\n" + + "\t\\/ op2\n" + + "\t\\/ op3\n" + + "\t\\/ op4\n" + + "\t\\/ op5\n" + + "===="; + compare(expected, machine); + } + + @Test + public void testAssignSequentialSubstitutionNested() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x,y,z\n" + + "INVARIANT x = 1 & y = 3 & z = 0\n" + + "INITIALISATION x := 1 ; y := x || z := x \n" + + "OPERATIONS\n" + + " op1 = BEGIN y := x ; z := 5 || x := y * z END; \n" + + " op2 = BEGIN y := x || z := y ; x := x + y + z ; ANY q WHERE q : INT & x = 5 & y = 6 THEN skip END END; \n" + + " op3 = BEGIN y := x || z := y ; x := x + y + z || ANY q WHERE q : INT & x = 5 & y = 6 THEN skip END END; \n" + + " op4 = BEGIN y := x || z := y || x := x + y + z || ANY q WHERE q : INT & x = 5 & y = 6 THEN skip END END; \n" + + " op5 = BEGIN BEGIN y := x END ; BEGIN x := y END ; SELECT x = 5 & z = 6 THEN z := x + y END END \n" + + "END"; + + String expected = "---- MODULE test ----\n" + + "EXTENDS Integers\n" + + "VARIABLES x, y, z\n" + + "Invariant1 == x = 1\n" + + "Invariant2 == y = 3\n" + + "Invariant3 == z = 0\n" + + "Init == x = 1 /\\ y = x /\\ z = x\n" + + "\n" + + "op1 == y' = x /\\ z' = 5 /\\ x' = y' * z\n" + + "\n" + + "op2 == y' = x /\\ z' = y /\\ x' = x + y' + z' /\\ \\E q \\in (-1..3) : x' = 5 /\\ y' = 6 /\\ TRUE\n" + + "\n" + + "op3 == y' = x /\\ z' = y /\\ x' = x + y' + z' /\\ \\E q \\in (-1..3) : x = 5 /\\ y' = 6 /\\ TRUE\n" + + "\n" + + "op4 == y' = x /\\ z' = y /\\ x' = x + y + z /\\ \\E q \\in (-1..3) : x = 5 /\\ y = 6 /\\ TRUE\n" + + "\n" + + "op5 == y' = x /\\ x' = y' /\\ (((x' = 5 /\\ z = 6) /\\ z' = x' + y'))\n" + + "\n" + + "Next == \\/ op1\n" + + "\t\\/ op2\n" + + "\t\\/ op3\n" + + "\t\\/ op4\n" + + "\t\\/ op5\n" + + "===="; + compare(expected, machine); + } + + @Test + public void testBecomesElementOfSequentialSubstitution() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x,y\n" + + "INVARIANT x = 1 & y = 3 \n" + + "INITIALISATION x := 1 ; y := x \n" + + "OPERATIONS\n" + + " op1 = PRE x < 6 THEN x :: 4..6 ; y := x + 1 END; \n" + + " op2 = PRE x < 6 THEN x :: 4..6 || y := x + 1 END; \n" + + " op3 = PRE x < 6 THEN x := 1 ; y :: {x} END; \n" + + " op4 = PRE x < 6 THEN x := 1 || y :: {x} END \n" + + "END"; + + String expected = "---- MODULE test ----\n" + + "EXTENDS Naturals\n" + + "VARIABLES x, y\n" + + "Invariant1 == x = 1\n" + + "Invariant2 == y = 3\n" + + "Init == x = 1 /\\ y = x\n" + + "\n" + + "op1 == x < 6\n" + + "\t/\\ (x' \\in (4 .. 6) /\\ y' = x' + 1)\n" + + "\n" + + "op2 == x < 6\n" + + "\t/\\ (x' \\in (4 .. 6) /\\ y' = x + 1)\n" + + "\n" + + "op3 == x < 6\n" + + "\t/\\ (x' = 1 /\\ y' \\in {x'})\n" + + "\n" + + "op4 == x < 6\n" + + "\t/\\ (x' = 1 /\\ y' \\in {x})\n" + + "\n" + + "Next == \\/ op1\n" + + "\t\\/ op2\n" + + "\t\\/ op3\n" + + "\t\\/ op4\n" + + "===="; + compare(expected, machine); + } + + @Test + public void testBecomesSuchSequentialSubstitution() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x,y\n" + + "INVARIANT x = 1 & y = 3 \n" + + "INITIALISATION x := 1 ; y := x \n" + + "OPERATIONS\n" + + " op1 = BEGIN x : (x : 4..6) ; y := x END; \n" + + " op2 = BEGIN x : (x : 4..6) || y := x END; \n" + + " op3 = BEGIN x := 1 ; y : (x = y) END; \n" + + " op4 = BEGIN x := 1 || y : (x = y) END \n" + + "END"; + + String expected = "---- MODULE test ----\n" + + "EXTENDS Naturals\n" + + "VARIABLES x, y\n" + + "Invariant1 == x = 1\n" + + "Invariant2 == y = 3\n" + + "Init == x = 1 /\\ y = x\n" + + "\n" + + "op1 == x' \\in (4 .. 6) /\\ y' = x'\n" + + "\n" + + "op2 == x' \\in (4 .. 6) /\\ y' = x\n" + + "\n" + + "op3 == x' = 1 /\\ y' \\in {x'}\n" + + "\n" + + "op4 == x' = 1 /\\ y' \\in {x}\n" + + "\n" + + "Next == \\/ op1\n" + + "\t\\/ op2\n" + + "\t\\/ op3\n" + + "\t\\/ op4\n" + + "===="; + compare(expected, machine); + } + + @Test (expected = SubstitutionException.class) + public void testSimpleSequentialSubstitutionAssignedTwice() throws Exception { + String machine = "MACHINE test\n" + + "VARIABLES x,y\n" + + "INVARIANT x = 1 & y = 3 \n" + + "INITIALISATION x := 1 ; y := x ; x := y \n" + + "END"; + compare(null, machine); + } @Test public void testLet() throws Exception { diff --git a/src/test/java/de/tlc4b/tlc/integration/BasicTest.java b/src/test/java/de/tlc4b/tlc/integration/BasicTest.java index b3fe17567887f460a9e6a327ec87f407da99c078..b61ef90e520631256c6415abbdea2d835b307b14 100644 --- a/src/test/java/de/tlc4b/tlc/integration/BasicTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/BasicTest.java @@ -1,46 +1,48 @@ package de.tlc4b.tlc.integration; -import static org.junit.Assert.assertEquals; - import java.io.File; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import de.tlc4b.tlc.TLCResults.TLCResult; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.TestPair; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; -import static de.tlc4b.tlc.TLCResults.TLCResult.NoError; +import static de.tlc4b.TLC4BOption.DFID; import static de.tlc4b.util.TestUtil.test; +import static org.junit.Assert.assertEquals; -@RunWith(PolySuite.class) -public class BasicTest extends AbstractParseMachineTest { - +@RunWith(Parameterized.class) +public class BasicTest { private final File machine; - private final TLCResult error; - public BasicTest(File machine, TLCResult result) { + public BasicTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.NoError, test(a)); + } + + @Test + public void testRunTLCDFS() throws Exception { + String[] a = new String[] { machine.getPath(), DFID.cliArg(), "20" }; + assertEquals(TLCResult.NoError, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(NoError, "./src/test/resources/composition/sees")); - list.add(new TestPair(NoError, "./src/test/resources/composition/sees2")); - list.add(new TestPair(NoError, "./src/test/resources/basics")); - list.add(new TestPair(NoError, "./src/test/resources/laws")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static List<File> data() { + List<File> machines = new ArrayList<>(); + machines.addAll(Arrays.asList(TestUtil.getMachines("./src/test/resources/composition/sees"))); + machines.addAll(Arrays.asList(TestUtil.getMachines("./src/test/resources/composition/sees2"))); + machines.addAll(Arrays.asList(TestUtil.getMachines("./src/test/resources/basics"))); + machines.addAll(Arrays.asList(TestUtil.getMachines("./src/test/resources/laws"))); + return machines; } } diff --git a/src/test/java/de/tlc4b/tlc/integration/ErrorTest.java b/src/test/java/de/tlc4b/tlc/integration/ErrorTest.java index 1a85190a9bc34b6cb627874997562adbffddeb56..d811883b4e778d1562bdf28fe4ead22783ae9840 100644 --- a/src/test/java/de/tlc4b/tlc/integration/ErrorTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/ErrorTest.java @@ -37,7 +37,7 @@ public class ErrorTest { @Test public void testNoFile() throws Exception { String[] a = new String[] { "./src/test/resources/errors/NoFile.mch" }; - assertEquals(null, test(a)); + assertNull(test(a)); } @Test @@ -46,7 +46,6 @@ public class ErrorTest { assertEquals(NoError, test(a)); } - @Ignore @Test public void testEnumerationError() throws Exception { String[] a = new String[] { "./src/test/resources/errors/EnumerationError.mch" }; diff --git a/src/test/java/de/tlc4b/tlc/integration/LTLTest.java b/src/test/java/de/tlc4b/tlc/integration/LTLTest.java index 8cbe47c53665240206a277df524e7d86ea96b913..63f87ae87de9945aec9ddcb9bb5a6e4240ffcc21 100644 --- a/src/test/java/de/tlc4b/tlc/integration/LTLTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/LTLTest.java @@ -20,43 +20,43 @@ public class LTLTest { @Test public void testCounterLTL() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\CounterLTL.mch" }; + String[] a = new String[] { "src/test/resources/ltl/CounterLTL.mch" }; assertEquals(NoError, test(a)); } @Test public void testCounterError() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\CounterError.mch" }; + String[] a = new String[] { "src/test/resources/ltl/CounterError.mch" }; assertEquals(TemporalPropertyViolation, test(a)); } @Test public void testFairnessCounterLTL() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\FairnessCounter.mch" }; + String[] a = new String[] { "src/test/resources/ltl/FairnessCounter.mch" }; assertEquals(NoError, test(a)); } @Test public void testUniversalQuantificaitonLTL() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\UniveralQuatification.mch" }; + String[] a = new String[] { "src/test/resources/ltl/UniveralQuatification.mch" }; assertEquals(TemporalPropertyViolation, test(a)); } @Test public void testExistentialQuantificationLTL() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\ExistentialQuantification.mch" }; + String[] a = new String[] { "src/test/resources/ltl/ExistentialQuantification.mch" }; assertEquals(NoError, test(a)); } @Test public void testFairnessParameter() throws Exception { - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\Fairness_Parameter.mch" }; + String[] a = new String[] { "src/test/resources/ltl/Fairness_Parameter.mch" }; assertEquals(NoError, test(a)); } @Test public void testLTLStatePropertyViolation() throws Exception{ - String[] a = new String[] { ".\\src\\test\\resources\\ltl\\StatePropertyViolation.mch" }; + String[] a = new String[] { "src/test/resources/ltl/StatePropertyViolation.mch" }; assertEquals(TemporalPropertyViolation, test(a)); } diff --git a/src/test/java/de/tlc4b/tlc/integration/SpecialTest.java b/src/test/java/de/tlc4b/tlc/integration/SpecialTest.java index a078bd7eff1b03b98da268967fc54aeda4b73399..cf37f5cc387256bb8d6b88bb378e5d44248f1f3d 100644 --- a/src/test/java/de/tlc4b/tlc/integration/SpecialTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/SpecialTest.java @@ -1,11 +1,18 @@ package de.tlc4b.tlc.integration; -import static org.junit.Assert.assertEquals; +import static de.tlc4b.TLC4BOption.*; import static de.tlc4b.tlc.TLCResults.TLCResult.*; import static de.tlc4b.util.TestUtil.test; +import static de.tlc4b.util.TestUtil.testWithTrace; +import static org.junit.Assert.*; import org.junit.Test; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + public class SpecialTest { @@ -13,7 +20,7 @@ public class SpecialTest { public void testConstantSetup() throws Exception { String[] a = new String[] { "./src/test/resources/special/ConstantSetup.mch", - "-constantsSetup", "(a = 1 & b = 1) or (a = 1 & b = 2)" }; + "-constantssetup", "(a = 1 & b = 1) or (a = 1 & b = 2)" }; assertEquals(NoError, test(a)); } @@ -21,7 +28,7 @@ public class SpecialTest { public void testConstantSetup2() throws Exception { String[] a = new String[] { "./src/test/resources/special/ConstantSetup.mch", - "-constantsSetup", "a = 1 & b = 1" }; + "-constantssetup", "a = 1 & b = 1" }; assertEquals(NoError, test(a)); } @@ -29,7 +36,7 @@ public class SpecialTest { public void testConstantSetup3() throws Exception { String[] a = new String[] { "./src/test/resources/special/ConstantSetup.mch", - "-constantsSetup", "(a = 1 & b = 1) or (a = 2 & b = 2)" }; + "-constantssetup", "(a = 1 & b = 1) or (a = 2 & b = 2)" }; assertEquals(NoError, test(a)); } @@ -37,7 +44,7 @@ public class SpecialTest { public void testConstantSetupFile2() throws Exception { String[] a = new String[] { "./src/test/resources/special/ConstantsSetup2.mch", - "-constantsSetup", "a = {(1,TRUE)}" }; + "-constantssetup", "a = {(1,TRUE)}" }; assertEquals(NoError, test(a)); } @@ -54,6 +61,46 @@ public class SpecialTest { "./src/test/resources/special/LoadDefinitions.mch"}; assertEquals(NoError, test(a)); } - + + @Test + public void testCustomOutputDir() throws Exception { + Path specialDir = Paths.get("./src/test/resources/special/veryspecialoutput"); + String[] a = new String[] { "./src/test/resources/errors/InvariantError.mch", OUTPUT.cliArg(), specialDir.toString()}; + assertEquals(InvariantViolation, testWithTrace(a)); + + assertTrue(Files.deleteIfExists(specialDir.resolve("InvariantError.tla"))); + assertTrue(Files.deleteIfExists(specialDir.resolve("InvariantError.cfg"))); + assertTrue(Files.deleteIfExists(specialDir.resolve("InvariantError.tla.trace"))); + assertTrue(Files.deleteIfExists(specialDir)); + } + + @Test + public void testLogFile() throws Exception { + Path logFile = Paths.get("./src/test/resources/special/log.csv"); + Path machineFile = Paths.get("./src/test/resources/special/SimpleForLog.mch"); + Path tracePath = Paths.get("./src/test/resources/special/SimpleForLog/SimpleForLog.tla.trace"); + logFile.toFile().delete(); + + String[] a = new String[] { machineFile.toString(), LOG.cliArg(), logFile.toString(), COVERAGE.cliArg()}; + assertEquals(InvariantViolation, testWithTrace(a)); + + List<String> lines = Files.readAllLines(logFile); + assertEquals(lines.size(), 12); + assertEquals(lines.get(0), "Machine File;" + machineFile.toRealPath()); + assertTrue(lines.get(1).startsWith("TLC Model Checking Time (s);")); + assertTrue(lines.get(2).startsWith("Parsing Time Of B machine (ms);")); + assertTrue(lines.get(3).startsWith("Translation Time (ms);")); + assertTrue(lines.get(4).startsWith("Model Checking Time (ms);")); + assertEquals(lines.get(5), "TLC Result;Invariant Violation"); + assertEquals(lines.get(6), "States analysed;5"); + assertEquals(lines.get(7), "Transitions fired;5"); + assertEquals(lines.get(8), "Violated Definition;Invariant1"); + assertEquals(lines.get(9), "Violated Assertions;"); + assertEquals(lines.get(10), "Operation Coverage;inc;8"); + assertEquals(lines.get(11), "Trace File;" + tracePath.toRealPath()); + + assertTrue(Files.deleteIfExists(tracePath)); + assertTrue(Files.deleteIfExists(logFile)); + } } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/AssertionErrorTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/AssertionErrorTest.java index 4f405b4476a061e80438526416d6fb3b563b706d..f3f341c84ef4359812b7b1bd2c97d25157eae481 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/AssertionErrorTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/AssertionErrorTest.java @@ -1,43 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; import java.io.File; -import java.util.ArrayList; import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; -import de.tlc4b.util.TestPair; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import static de.tlc4b.tlc.TLCResults.TLCResult.AssertionError; import static de.tlc4b.util.TestUtil.test; import static org.junit.Assert.assertEquals; -@RunWith(PolySuite.class) -public class AssertionErrorTest extends AbstractParseMachineTest { - +@RunWith(Parameterized.class) +public class AssertionErrorTest { private final File machine; - private final TLCResult error; - public AssertionErrorTest(File machine, TLCResult result) { + public AssertionErrorTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.AssertionError, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(AssertionError, "build/prob_examples/public_examples/TLC/AssertionError")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/AssertionError"); } } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/CoverageTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/CoverageTest.java index 4461c50d825d25c9fb9d27352b62e7b4345bdfa9..98be04caa87af42dbacc4fee2e0d379d131c2415 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/CoverageTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/CoverageTest.java @@ -2,25 +2,22 @@ package de.tlc4b.tlc.integration.probprivate; import java.io.File; import java.util.ArrayList; +import java.util.List; import de.tlc4b.TLC4B; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; import tlc2.TLCGlobals; -@RunWith(PolySuite.class) -public class CoverageTest extends AbstractParseMachineTest { - +@RunWith(Parameterized.class) +public class CoverageTest { private final File machine; - public CoverageTest(File machine, TLCResult result) { + public CoverageTest(File machine) { this.machine = machine; } @@ -36,20 +33,17 @@ public class CoverageTest extends AbstractParseMachineTest { TLC4B.test(a, true); } - @Config - public static Configuration getConfig() { - final ArrayList<String> list = new ArrayList<String>(); - final ArrayList<String> ignoreList = new ArrayList<String>(); - list.add("build/prob_examples/public_examples/TLC/"); - - list.add("./src/test/resources/"); - ignoreList.add("./src/test/resources/compound/"); - ignoreList.add("./src/test/resources/other/"); - ignoreList.add("./src/test/resources/test/"); - ignoreList.add("./src/test/resources/testing/"); - ignoreList.add("./src/test/resources/todo/"); - ignoreList.add("./src/test/resources/bugs/"); - return getConfiguration2(list, ignoreList); + @Parameterized.Parameters(name = "{0}") + public static List<File> data() { + List<File> machines = new ArrayList<>(); + machines.addAll(TestUtil.getMachinesRecursively("build/prob_examples/public_examples/TLC/")); + // The subdirectories bugs, compound, and test are intentionally not included here. + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/basics/")); + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/composition/")); + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/errors/")); + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/laws/")); + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/ltl/")); + machines.addAll(TestUtil.getMachinesRecursively("src/test/resources/special/")); + return machines; } - } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/DeadlockTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/DeadlockTest.java index 6d01d2a02ec6dab732efdce7bb7e081fba9d8698..23dd45b37ff5ca636dd7e3beccaed5707f7a1e58 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/DeadlockTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/DeadlockTest.java @@ -1,44 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; -import static de.tlc4b.tlc.TLCResults.TLCResult.*; -import static de.tlc4b.util.TestUtil.test; -import static org.junit.Assert.assertEquals; - import java.io.File; -import java.util.ArrayList; + +import de.tlc4b.tlc.TLCResults.TLCResult; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.TestPair; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; - -@RunWith(PolySuite.class) -public class DeadlockTest extends AbstractParseMachineTest { +import static de.tlc4b.util.TestUtil.test; +import static org.junit.Assert.assertEquals; +@RunWith(Parameterized.class) +public class DeadlockTest { private final File machine; - private final TLCResult error; - public DeadlockTest(File machine, TLCResult result) { + public DeadlockTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.Deadlock, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(Deadlock, - "build/prob_examples/public_examples/TLC/Deadlock")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/Deadlock"); } } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/GoalTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/GoalTest.java index d026d9c9ecb8eb25c3353b71b6664562ab953265..509beb4c48c50101320cc4459a6b232fd038ae96 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/GoalTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/GoalTest.java @@ -1,44 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; -import static org.junit.Assert.assertEquals; -import static de.tlc4b.tlc.TLCResults.TLCResult.*; -import static de.tlc4b.util.TestUtil.test; - import java.io.File; -import java.util.ArrayList; + +import de.tlc4b.tlc.TLCResults.TLCResult; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.TestPair; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; - -@RunWith(PolySuite.class) -public class GoalTest extends AbstractParseMachineTest { +import static de.tlc4b.util.TestUtil.test; +import static org.junit.Assert.assertEquals; +@RunWith(Parameterized.class) +public class GoalTest { private final File machine; - private final TLCResult error; - public GoalTest(File machine, TLCResult result) { + public GoalTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.Goal, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(Goal, - "build/prob_examples/public_examples/TLC/GOAL")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/GOAL"); } } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/InvariantViolationTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/InvariantViolationTest.java index c395f3908b0deebacfc50b1591c7a383f53b7b04..c83ca85f536b0f9956a185c45a922f56e0550fa9 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/InvariantViolationTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/InvariantViolationTest.java @@ -1,44 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; -import static de.tlc4b.tlc.TLCResults.TLCResult.*; -import static de.tlc4b.util.TestUtil.test; -import static org.junit.Assert.assertEquals; - import java.io.File; -import java.util.ArrayList; + +import de.tlc4b.tlc.TLCResults.TLCResult; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.TestPair; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; - -@RunWith(PolySuite.class) -public class InvariantViolationTest extends AbstractParseMachineTest { +import static de.tlc4b.util.TestUtil.test; +import static org.junit.Assert.assertEquals; +@RunWith(Parameterized.class) +public class InvariantViolationTest { private final File machine; - private final TLCResult error; - public InvariantViolationTest(File machine, TLCResult result) { + public InvariantViolationTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.InvariantViolation, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(InvariantViolation, - "build/prob_examples/public_examples/TLC/InvariantViolation")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/InvariantViolation"); } } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/NoErrorTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/NoErrorTest.java index e5c0fe4d6c31cd8fe9f8b68deb26340bfcfa6615..1c42dae54d11265da97ffcaa580a39a52d8a475b 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/NoErrorTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/NoErrorTest.java @@ -1,45 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; -import static de.tlc4b.tlc.TLCResults.TLCResult.*; -import static de.tlc4b.util.TestUtil.test; -import static org.junit.Assert.assertEquals; - import java.io.File; -import java.util.ArrayList; + +import de.tlc4b.tlc.TLCResults.TLCResult; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.TestPair; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; - -@RunWith(PolySuite.class) -public class NoErrorTest extends AbstractParseMachineTest { +import static de.tlc4b.util.TestUtil.test; +import static org.junit.Assert.assertEquals; +@RunWith(Parameterized.class) +public class NoErrorTest { private final File machine; - private final TLCResult error; - public NoErrorTest(File machine, TLCResult result) { + public NoErrorTest(File machine) { this.machine = machine; - this.error = result; } @Test public void testRunTLC() throws Exception { String[] a = new String[] { machine.getPath() }; - assertEquals(error, test(a)); + assertEquals(TLCResult.NoError, test(a)); } - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(NoError, - "build/prob_examples/public_examples/TLC/NoError")); - return getConfiguration(list); + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/NoError"); } - } diff --git a/src/test/java/de/tlc4b/tlc/integration/probprivate/WellDefinednessTest.java b/src/test/java/de/tlc4b/tlc/integration/probprivate/WellDefinednessTest.java index 2004cd1f1d4e88bf6a9a2d450cd0f771b868db01..84dd04ed20e9cfae29e583ff25cf360038e1acea 100644 --- a/src/test/java/de/tlc4b/tlc/integration/probprivate/WellDefinednessTest.java +++ b/src/test/java/de/tlc4b/tlc/integration/probprivate/WellDefinednessTest.java @@ -1,43 +1,33 @@ package de.tlc4b.tlc.integration.probprivate; import java.io.File; -import java.util.ArrayList; import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.AbstractParseMachineTest; -import de.tlc4b.util.PolySuite; -import de.tlc4b.util.PolySuite.Config; -import de.tlc4b.util.PolySuite.Configuration; -import de.tlc4b.util.TestPair; +import de.tlc4b.util.TestUtil; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; -import static de.tlc4b.tlc.TLCResults.TLCResult.WellDefinednessError; import static de.tlc4b.util.TestUtil.test; import static org.junit.Assert.assertEquals; -@RunWith(PolySuite.class) -public class WellDefinednessTest extends AbstractParseMachineTest { - - private final File machine; - private final TLCResult error; - - public WellDefinednessTest(File machine, TLCResult result) { - this.machine = machine; - this.error = result; - } - - @Test - public void testRunTLC() throws Exception { - String[] a = new String[] { machine.getPath(), "-wdcheck" }; - assertEquals(error, test(a)); - } - - @Config - public static Configuration getConfig() { - final ArrayList<TestPair> list = new ArrayList<TestPair>(); - list.add(new TestPair(WellDefinednessError, "build/prob_examples/public_examples/TLC/WellDefinednessError")); - return getConfiguration(list); - } +@RunWith(Parameterized.class) +public class WellDefinednessTest { + private final File machine; + + public WellDefinednessTest(File machine) { + this.machine = machine; + } + + @Test + public void testRunTLC() throws Exception { + String[] a = new String[] { machine.getPath(), "-wdcheck" }; + assertEquals(TLCResult.WellDefinednessError, test(a)); + } + + @Parameterized.Parameters(name = "{0}") + public static File[] data() { + return TestUtil.getMachines("build/prob_examples/public_examples/TLC/WellDefinednessError"); + } } diff --git a/src/test/java/de/tlc4b/typechecking/TestTypechecker.java b/src/test/java/de/tlc4b/typechecking/TestTypechecker.java index cab56aadf119a6e31054dc3b823c1bbd0f506c9f..f00acbee2e660bcc1f4f727008004f53d53910ba 100644 --- a/src/test/java/de/tlc4b/typechecking/TestTypechecker.java +++ b/src/test/java/de/tlc4b/typechecking/TestTypechecker.java @@ -12,19 +12,19 @@ import de.tlc4b.btypes.BType; public class TestTypechecker { - Hashtable<String, BType> parameters; - Hashtable<String, BType> constants; - Hashtable<String, BType> variables; + final Hashtable<String, BType> parameters; + final Hashtable<String, BType> constants; + final Hashtable<String, BType> variables; public TestTypechecker(String machine) throws BException { - parameters = new Hashtable<String, BType>(); - constants = new Hashtable<String, BType>(); - variables = new Hashtable<String, BType>(); + parameters = new Hashtable<>(); + constants = new Hashtable<>(); + variables = new Hashtable<>(); BParser parser = new BParser("Test"); Start start; try { - start = parser.parse(machine, false); + start = parser.parseMachine(machine); } catch (BCompoundException e) { throw e.getFirstException(); } @@ -33,8 +33,8 @@ public class TestTypechecker { c.analyseMachine(); Typechecker t = new Typechecker(c); - for (String name : c.getSetParamter().keySet()) { - parameters.put(name, t.getType(c.getSetParamter().get(name))); + for (String name : c.getSetParameter().keySet()) { + parameters.put(name, t.getType(c.getSetParameter().get(name))); } for (String name : c.getScalarParameter().keySet()) { diff --git a/src/test/java/de/tlc4b/util/AbstractParseMachineTest.java b/src/test/java/de/tlc4b/util/AbstractParseMachineTest.java deleted file mode 100644 index d42a95784f371448ec170fa68541b09deda09940..0000000000000000000000000000000000000000 --- a/src/test/java/de/tlc4b/util/AbstractParseMachineTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package de.tlc4b.util; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -import de.tlc4b.tlc.TLCResults.TLCResult; -import de.tlc4b.util.PolySuite.Configuration; - -public abstract class AbstractParseMachineTest { - - private static final class MachineFilenameFilter implements FilenameFilter { - private static final String[] MACHINE_SUFFIX = { ".mch" }; - - public boolean accept(final File dir, final String name) { - for (int i = 0; i < MACHINE_SUFFIX.length; i++) { - if (name.endsWith(MACHINE_SUFFIX[i])) { - return true; - } - } - return false; - } - } - - protected static File[] getMachines(String path) { - final File dir = new File(path); - return dir.listFiles(new MachineFilenameFilter()); - } - - protected static File[] getMachinesRecursively(String path, ArrayList<String> ignoreList) { - File[] files = walk(path, ignoreList).toArray(new File[0]); - return files; - } - - private static ArrayList<File> walk(String path, ArrayList<String> ignoreList) { - File root = new File(path); - File[] list = root.listFiles(); - - ArrayList<File> files = new ArrayList<File>(); - if (list == null) - return files; - - for (File f : list) { - if (f.isDirectory()) { - boolean visitDir = true; - for (String string : ignoreList) { - File ignore = new File(string); - try { - if(f.getCanonicalPath().equals(ignore.getCanonicalPath())){ - visitDir = false; - } - } catch (IOException e) { - visitDir = false; - } - } - if(visitDir){ - files.addAll(walk(f.getAbsolutePath(),ignoreList)); - } - - } else { - String name =f.getName(); - if (name.endsWith(".mch")) { - files.add(f); - } - } - } - return files; - } - - protected static Configuration getConfiguration2(ArrayList<String> list, ArrayList<String> ignoreList) { - final ArrayList<File> allMachines = new ArrayList<File>(); - - final ArrayList<TLCResult> expectedValues = new ArrayList<TLCResult>(); - for (String path : list) { - File[] machines = getMachinesRecursively(path, ignoreList); - allMachines.addAll(Arrays.asList(machines)); - for (int i = 0; i < machines.length; i++) { - expectedValues.add(TLCResult.NoError); - } - } - - return new Configuration() { - public int size() { - return allMachines.size(); - } - - public File getTestValue(int index) { - return allMachines.get(index); - } - - public String getTestName(int index) { - return allMachines.get(index).getName(); - } - - public TLCResult getExpectedValue(int index) { - return expectedValues.get(index); - } - }; - } - - protected static Configuration getConfiguration(ArrayList<TestPair> list) { - final ArrayList<File> allMachines = new ArrayList<File>(); - - final ArrayList<TLCResult> expectedValues = new ArrayList<TLCResult>(); - for (TestPair testPair : list) { - File[] machines = getMachines(testPair.getPath()); - allMachines.addAll(Arrays.asList(machines)); - for (int i = 0; i < machines.length; i++) { - expectedValues.add(testPair.getResult()); - } - } - - return new Configuration() { - public int size() { - return allMachines.size(); - } - - public File getTestValue(int index) { - return allMachines.get(index); - } - - public String getTestName(int index) { - return allMachines.get(index).getName(); - } - - public TLCResult getExpectedValue(int index) { - return expectedValues.get(index); - } - }; - } - -} \ No newline at end of file diff --git a/src/test/java/de/tlc4b/util/PolySuite.java b/src/test/java/de/tlc4b/util/PolySuite.java deleted file mode 100644 index 81574f75af9ba9e307da6a57697169a5392e5fad..0000000000000000000000000000000000000000 --- a/src/test/java/de/tlc4b/util/PolySuite.java +++ /dev/null @@ -1,140 +0,0 @@ -package de.tlc4b.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.junit.runner.Runner; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.Suite; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; -import org.junit.runners.model.TestClass; - -public class PolySuite extends Suite { - - // ////////////////////////////// - // Public helper interfaces - - /** - * Annotation for a method which returns a {@link Configuration} - * to be injected into the test class constructor - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public static @interface Config { - } - - public static interface Configuration { - int size(); - Object getTestValue(int index); - Object getExpectedValue(int index); - String getTestName(int index); - } - - // ////////////////////////////// - // Fields - - private final List<Runner> runners; - - // ////////////////////////////// - // Constructor - - /** - * Only called reflectively. Do not use programmatically. - * @param c the test class - * @throws Throwable if something bad happens - */ - public PolySuite(Class<?> c) throws Throwable { - super(c, Collections.<Runner>emptyList()); - TestClass testClass = getTestClass(); - Class<?> jTestClass = testClass.getJavaClass(); - Configuration configuration = getConfiguration(testClass); - List<Runner> runners = new ArrayList<Runner>(); - for (int i = 0, size = configuration.size(); i < size; i++) { - SingleRunner runner = new SingleRunner(jTestClass, configuration.getTestValue(i), configuration.getTestName(i), configuration.getExpectedValue(i)); - runners.add(runner); - } - this.runners = runners; - } - - // ////////////////////////////// - // Overrides - - @Override - protected List<Runner> getChildren() { - return runners; - } - - // ////////////////////////////// - // Private - - private Configuration getConfiguration(TestClass testClass) throws Throwable { - return (Configuration) getConfigMethod(testClass).invokeExplosively(null); - } - - private FrameworkMethod getConfigMethod(TestClass testClass) { - List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Config.class); - if (methods.isEmpty()) { - throw new IllegalStateException("@" + Config.class.getSimpleName() + " method not found"); - } - if (methods.size() > 1) { - throw new IllegalStateException("Too many @" + Config.class.getSimpleName() + " methods"); - } - FrameworkMethod method = methods.get(0); - int modifiers = method.getMethod().getModifiers(); - if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { - throw new IllegalStateException("@" + Config.class.getSimpleName() + " method \"" + method.getName() + "\" must be public static"); - } - return method; - } - - // ////////////////////////////// - // Helper classes - - private static class SingleRunner extends BlockJUnit4ClassRunner { - - private final Object testVal; - private final Object expectedVal; - private final String testName; - - SingleRunner(Class<?> testClass, Object testVal, String testName, Object expectedVal) throws InitializationError { - super(testClass); - this.testVal = testVal; - this.expectedVal = expectedVal; - this.testName = testName; - } - - @Override - protected Object createTest() throws Exception { - return getTestClass().getOnlyConstructor().newInstance(testVal, expectedVal); - } - - @Override - protected String getName() { - return testName; - } - - @Override - protected String testName(FrameworkMethod method) { - return testName + ": " + method.getName(); - } - - @Override - protected void validateConstructor(List<Throwable> errors) { - validateOnlyOneConstructor(errors); - } - - @Override - protected Statement classBlock(RunNotifier notifier) { - return childrenInvoker(notifier); - } - } -} \ No newline at end of file diff --git a/src/test/java/de/tlc4b/util/TestPair.java b/src/test/java/de/tlc4b/util/TestPair.java deleted file mode 100644 index 8bdc29b34a9d39368025f3a1a5831f140c85d2e1..0000000000000000000000000000000000000000 --- a/src/test/java/de/tlc4b/util/TestPair.java +++ /dev/null @@ -1,22 +0,0 @@ -package de.tlc4b.util; - -import de.tlc4b.tlc.TLCResults.TLCResult; - - -public class TestPair { - private final TLCResult error; - private final String path; - - public TestPair(TLCResult error, String path) { - this.error = error; - this.path = path; - } - - public TLCResult getResult() { - return error; - } - - public String getPath() { - return path; - } -} \ No newline at end of file diff --git a/src/test/java/de/tlc4b/util/TestUtil.java b/src/test/java/de/tlc4b/util/TestUtil.java index 765859b5fa4fc9507f268216c9a4d6164c127b4e..a9b91d986266cc798ef7f437faac93f53380387e 100644 --- a/src/test/java/de/tlc4b/util/TestUtil.java +++ b/src/test/java/de/tlc4b/util/TestUtil.java @@ -5,24 +5,56 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import de.be4.classicalb.core.parser.exceptions.BCompoundException; -import de.be4.classicalb.core.parser.exceptions.BException; -import de.tla2b.exceptions.FrontEndException; import de.tla2b.exceptions.TLA2BException; -import de.tlc4b.TLC4B; import de.tlc4b.TLC4BGlobals; import de.tlc4b.Translator; import de.tlc4b.tlc.TLCResults.TLCResult; import util.ToolIO; +import static de.tlc4b.TLC4BOption.NOTRACE; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestUtil { + private static final String MCH_SUFFIX = ".mch"; + private static final Pattern TRANSLATED_LTL_FORMULA_PATTERN = Pattern.compile("^ltl == (.*)$", Pattern.MULTILINE); + + public static File[] getMachines(String path) { + return new File(path).listFiles((dir, name) -> name.endsWith(MCH_SUFFIX)); + } + + public static List<File> getMachinesRecursively(String path) { + File root = new File(path); + File[] list = root.listFiles(); + + List<File> files = new ArrayList<>(); + if (list == null) { + return files; + } + + for (File f : list) { + if (f.isDirectory()) { + files.addAll(getMachinesRecursively(f.getAbsolutePath())); + } else { + String name = f.getName(); + if (name.endsWith(MCH_SUFFIX)) { + files.add(f); + } + } + } + + return files; + } public static void compare(final String expectedModule, final String machineString) throws BCompoundException, TLA2BException { TLC4BGlobals.setForceTLCToEvalConstants(false); @@ -51,19 +83,6 @@ public class TestUtil { assertEquals(expectedB, actualB); } - public static void tryTranslating(final String machineString) throws BException { - TLC4BGlobals.setForceTLCToEvalConstants(false); - ToolIO.setMode(ToolIO.TOOL); - Translator b2tlaTranslator; - try { - b2tlaTranslator = new Translator(machineString); - b2tlaTranslator.translate(); - } catch (BCompoundException e) { - throw e.getFirstException(); - } - - } - public static String translateTLA2B(String moduleName, String tlaString, String configString) throws TLA2BException { return de.tla2bAst.Translator.translateModuleString(moduleName, tlaString, configString); @@ -72,9 +91,20 @@ public class TestUtil { public static void compareLTLFormula(String expected, String machine, String ltlFormula) throws BCompoundException { Translator b2tlaTranslator = new Translator(machine, ltlFormula); b2tlaTranslator.translate(); - String translatedLTLFormula = b2tlaTranslator.getTranslatedLTLFormula(); - translatedLTLFormula = translatedLTLFormula.replaceAll("\\s", ""); - expected = expected.replaceAll("\\s", ""); + + // Extract the translated LTL formula from the complete TLA module. + Matcher matcher = TRANSLATED_LTL_FORMULA_PATTERN.matcher(b2tlaTranslator.getModuleString()); + boolean matches = matcher.find(); + String message = "Could not find LTL formula in translated TLA module"; + if (!matches) { + // Debugging help: if the LTL formula couldn't be found, + // do an assertEquals with the module string (which will always fail) + // so that the entire module string appears in the JUnit output and in IDEs, test reports, etc. + assertEquals(message, expected, b2tlaTranslator.getModuleString()); + } + assertTrue(message, matches); + + String translatedLTLFormula = matcher.group(1); assertEquals(expected, translatedLTLFormula); } @@ -84,62 +114,28 @@ public class TestUtil { String name = b2tlaTranslator.getMachineName(); translateTLA2B(name, b2tlaTranslator.getModuleString(), b2tlaTranslator.getConfigString()); + // TODO Check that re-translated B machine matches original input? } - public static void compareEqualsConfig(String expectedModule, String expectedConfig, String machine) + public static void compareModuleAndConfig(String expectedModule, String expectedConfig, String machine) throws Exception { Translator b2tlaTranslator = new Translator(machine); b2tlaTranslator.translate(); - String name = b2tlaTranslator.getMachineName(); - - // parse check - translateTLA2B(name, b2tlaTranslator.getModuleString(), b2tlaTranslator.getConfigString()); - assertEquals(expectedModule, b2tlaTranslator.getModuleString()); assertEquals(expectedConfig, b2tlaTranslator.getConfigString()); - } - - public static void compareModuleAndConfig(String expectedModule, String expectedConfig, String machine) - throws BCompoundException, TLA2BException { - Translator b2tlaTranslator = new Translator(machine); - b2tlaTranslator.translate(); - - // TODO include config file in back translation from TLA+ to B - - // String name = b2tlaTranslator.getMachineName(); - // StringBuilder sb1 = de.tla2b.translation.Tla2BTranslator - // .translateString(name, b2tlaTranslator.getModuleString(), - // b2tlaTranslator.getConfigString()); - // StringBuilder sb2 = de.tla2b.translation.Tla2BTranslator - // .translateString(name, expectedModule, expectedConfig); - // if (!sb2.toString().equals(sb1.toString())) { - // fail("expected:\n" + expectedModule + "\nbut was:\n" - // + b2tlaTranslator.getModuleString() + "\n\nexpected:\n" - // + expectedConfig + "\nbut was:\n" - // + b2tlaTranslator.getConfigString()); - // } - } - public static void compareEquals(String expected, String machine) throws BException { - try { - Translator b2tlaTranslator = new Translator(machine); - b2tlaTranslator.translate(); - assertEquals(expected, b2tlaTranslator.getModuleString()); - } catch (BCompoundException e) { - throw e.getFirstException(); - } + String name = b2tlaTranslator.getMachineName(); + // parse check + translateTLA2B(name, b2tlaTranslator.getModuleString(), b2tlaTranslator.getConfigString()); + // TODO Check that re-translated B machine matches original input? } - public static String translate(String machine) throws BException { - try { - Translator translator = new Translator(machine); - translator.translate(); - return translator.getModuleString(); - } catch (BCompoundException e) { - throw e.getFirstException(); - } + public static String translate(String machine) throws BCompoundException { + Translator translator = new Translator(machine); + translator.translate(); + return translator.getModuleString(); } public static TLCResult testString(String machineString) throws IOException { @@ -149,6 +145,13 @@ public class TestUtil { } public static TLCResult test(String[] args) throws IOException { + String[] newArgs = Arrays.copyOf(args, args.length + 1); + newArgs[args.length] = NOTRACE.cliArg(); + String runnerClassName = TLC4BTester.class.getCanonicalName(); + return runTLC(runnerClassName, newArgs); + } + + public static TLCResult testWithTrace(String[] args) throws IOException { String runnerClassName = TLC4BTester.class.getCanonicalName(); return runTLC(runnerClassName, args); } @@ -178,12 +181,12 @@ public class TestUtil { private static Process startJVM(final String mainClass, final String[] arguments) throws IOException { - String separator = System.getProperty("file.separator"); + String separator = FileSystems.getDefault().getSeparator(); String jvm = System.getProperty("java.home") + separator + "bin" + separator + "java"; String classpath = System.getProperty("java.class.path"); - List<String> command = new ArrayList<String>(); + List<String> command = new ArrayList<>(); command.add(jvm); command.add("-cp"); command.add(classpath); @@ -192,29 +195,13 @@ public class TestUtil { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); - Process process = processBuilder.start(); - return process; - } - - public static void testParse(String[] args, boolean deleteFiles) throws IOException, BCompoundException, FrontEndException { - TLC4BGlobals.resetGlobals(); - TLC4BGlobals.setDeleteOnExit(deleteFiles); - TLC4BGlobals.setCreateTraceFile(false); - TLC4BGlobals.setTestingMode(true); - // B2TLAGlobals.setCleanup(true); - TLC4B tlc4b = new TLC4B(); - tlc4b.process(args); - File module = new File(tlc4b.getBuildDir(), tlc4b.getMachineFileNameWithoutFileExtension() + ".tla"); - - // parse result - new de.tla2bAst.Translator(module.getCanonicalPath()); + return processBuilder.start(); } - } class StreamGobbler extends Thread { - private InputStream is; - private ArrayList<String> log; + private final InputStream is; + private final ArrayList<String> log; public ArrayList<String> getLog() { return log; @@ -222,14 +209,14 @@ class StreamGobbler extends Thread { StreamGobbler(InputStream is) { this.is = is; - this.log = new ArrayList<String>(); + this.log = new ArrayList<>(); } public void run() { try { - InputStreamReader isr = new InputStreamReader(is, "UTF-8"); + InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr); - String line = null; + String line; while ((line = br.readLine()) != null) { System.out.println("> " + line); log.add(line); diff --git a/src/test/resources/basics/SubstitutionsTest.mch b/src/test/resources/basics/SubstitutionsTest.mch index 919d8179c291cba40b304873150957b9221b681e..7f17fed0dc2b3e24510e18789eaeb41f25d426ab 100644 --- a/src/test/resources/basics/SubstitutionsTest.mch +++ b/src/test/resources/basics/SubstitutionsTest.mch @@ -1,12 +1,31 @@ MACHINE SubstitutionsTest -VARIABLES x -INVARIANT x : 1..5 -INITIALISATION x := 1 +VARIABLES x, y +INVARIANT x : 1..10 & y : 1..10 +INITIALISATION x := 1 ; y := x OPERATIONS op1 = PRE 1 = 1 THEN x := 2 END; op2 = LET a, b, c BE a = 1 & b : {1} & c = 2 IN x := 2 END; op3 = SELECT 1=1 THEN x := 1 WHEN 1=1 THEN x:=2 ELSE x:= 3 END; op4 = SELECT 1=1 THEN x := 1 WHEN 1=1 THEN x:=2 WHEN 1=1 THEN x:=3 ELSE x:= 4 END; -op5 = BEGIN LET p BE p = 2 IN x:= p END END +op5 = BEGIN LET p BE p = 2 IN x:= p END END; + +// test assert: +op6 = BEGIN x := 1 ; y := x + 1 END; +op7 = BEGIN x := 1 || y := x + 1 END; +op8 = SELECT x : 2..9 & y : 2..9 THEN x := y ; y := 1 END; +op9 = ANY z WHERE z = 5 & x : 2..9 & y : 2..9 THEN x := y || y := 1 END; +op10 = BEGIN x, y := x, x + 1 END; + +// test becomes element of: +op11 = PRE x < 6 THEN x :: 4..6 ; y := x + 1 END; +op12 = PRE x < 6 THEN x :: 4..6 || y := x + 1 END; +op13 = PRE x < 6 THEN x := 1 ; y :: {x} END; +op14 = PRE x < 6 THEN x := 1 || y :: {x} END; + +// test becomes such: +op15 = BEGIN x : (x : 4..6) ; y := x END; +op16 = BEGIN x : (x : 4..6) || y := x END; +op17 = BEGIN x := 1 ; y : (x = y) END; +op18 = BEGIN x := 1 || y : (x = y) END END \ No newline at end of file diff --git a/src/test/resources/special/SimpleForLog.mch b/src/test/resources/special/SimpleForLog.mch new file mode 100644 index 0000000000000000000000000000000000000000..e285feed38af3ce28b5f375f38133896922f1816 --- /dev/null +++ b/src/test/resources/special/SimpleForLog.mch @@ -0,0 +1,6 @@ +MACHINE SimpleForLog +VARIABLES i +INVARIANT i : 1..4 +INITIALISATION i := 1 +OPERATIONS inc = PRE i < 5 THEN i := succ(i) END +END \ No newline at end of file diff --git a/src/test/resources/testing/.DS_Store b/src/test/resources/testing/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 Binary files a/src/test/resources/testing/.DS_Store and /dev/null differ