diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.github/workflows/publish-library.yml b/.github/workflows/publish-library.yml new file mode 100644 index 0000000..6d0e7b5 --- /dev/null +++ b/.github/workflows/publish-library.yml @@ -0,0 +1,34 @@ + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +# GitHub recommends pinning actions to a commit SHA. +# To get a newer version, you will need to update the SHA. +# You can also reference a tag or branch, but the action may change without warning. + +name: Publish package to GitHub Packages +on: + release: + types: [created] +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'adopt' + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b + - name: Publish package + uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 + with: + arguments: publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b6985c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..943f0cb Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f398c33 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..65dcd68 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# 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 +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +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. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +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 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# 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. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +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. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/build.gradle b/lib/build.gradle new file mode 100644 index 0000000..4f2aaac --- /dev/null +++ b/lib/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'java-library' + id 'maven-publish' +} + + +targetCompatibility = "11" + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.eclipse.emf:org.eclipse.emf.ecore:+' +} + + +publishing { + publications { + myLibrary(MavenPublication) { + group = 'io.github.atlresearch' + artifactId 'emfmodelfuzzer' + version = '0.1' + + from components.java + } + } + + repositories { + maven { + name 'github' + url "https://maven.pkg.github.com/ATL-Research/EMFModelFuzzer" + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } +} diff --git a/lib/src/main/java/io/github/atlresearch/emfmodelfuzzer/SimpleEMFModelFuzzer.java b/lib/src/main/java/io/github/atlresearch/emfmodelfuzzer/SimpleEMFModelFuzzer.java new file mode 100644 index 0000000..d2d241a --- /dev/null +++ b/lib/src/main/java/io/github/atlresearch/emfmodelfuzzer/SimpleEMFModelFuzzer.java @@ -0,0 +1,384 @@ +package io.github.atlresearch.emfmodelfuzzer; + +import java.lang.Class; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.resource.Resource; +//import org.eclipse.papyrus.aof.core.impl.operation.Inspect; +//import org.eclipse.uml2.uml.UMLPackage; + +// TODO: enable CLEAR, ADD_MANY, and REMOVE_MANY +public class SimpleEMFModelFuzzer { + + private Resource modelToFuzz; + private Random random; + private boolean logToConsole; + + // set to true so that the next change is immediately undone + // remark: undoing will set it back to false + public boolean undo = false; + + public SimpleEMFModelFuzzer(Resource modelToFuzz, long seed, boolean logToConsole) { + this.modelToFuzz = modelToFuzz; + this.random = new Random(seed); + this.logToConsole = logToConsole; + } + + public static enum ManyChangeKind { + ADD, REMOVE, MOVE, + SET // REPLACE + // 2 still unsupported: + // ADD_MANY + // REMOVE_MANY (including CLEAR) + ; + } + + public static enum SingleChangeKind { + SET, SET_NULL, UNSET; + } + + // TODO: include elements that were discarded but can be readded later + private Object getPossibleValue(EStructuralFeature feature, List allContents) { + Object ret = null; + if(feature instanceof EAttribute) { + EClassifier type = feature.getEType(); + Class instanceClass = type.getInstanceClass(); + if(type instanceof EEnum) { + List literals = ((EEnum)type).getELiterals(); + ret = literals.get(random.nextInt(literals.size())).getInstance(); + } else if(instanceClass.equals(Integer.class) || instanceClass.equals(Integer.TYPE)) { + ret = random.nextInt(); + } else if(instanceClass.equals(String.class)) { + ret = "" + random.nextInt(); + } else if(instanceClass.equals(Double.class) || instanceClass.equals(Double.TYPE)) { + ret = random.nextDouble(); + } else if(instanceClass.equals(Boolean.class) || instanceClass.equals(Boolean.TYPE)) { + ret = random.nextBoolean(); + } else { + throw new UnsupportedOperationException("Cannot get a value of type " + type.getInstanceClass()); + } + } else { + if(random.nextBoolean()) { + // add existing + List candidates = new ArrayList(); + for(EObject o : allContents) { + if(feature.getEType().isInstance(o)) { + candidates.add(o); + } + } + if(candidates.size() > 0) { + ret = candidates.get(random.nextInt(candidates.size())); + } else { + ret = null; + } + } else { + // add new + EClass eClass = (EClass)feature.getEType(); + List subtypes = getSubtypes(eClass); + eClass = subtypes.get(random.nextInt(subtypes.size())); + ret = eClass.getEPackage().getEFactoryInstance().create(eClass); + } + } + return ret; + } + + private Map> subtypesByEClass = new HashMap>(); + + // & self + private List getSubtypes(EClass eClass) { + List ret = subtypesByEClass.get(eClass); + if(ret == null) { + ret = new ArrayList(); + for(Iterator i = eClass.eResource().getAllContents() ; i.hasNext() ; ) { + EObject e = i.next(); + if(e instanceof EClass) { + EClass ec = (EClass)e; + if(ec.getEAllSuperTypes().contains(eClass) && !ec.isAbstract()) { + ret.add(ec); + } + } + } + if(!eClass.isAbstract()) { + ret.add(eClass); + } + subtypesByEClass.put(eClass, ret); + } + return ret; + } + + private Map> featuresByEClass = new HashMap>(); + public Collection excludedFeatures = Arrays.asList( + // add feature name to ignore here + + +/* // UML specific excluded features + + // problem with these ones: some additional constraints beyond actual feature type are implemented in UML plugin (probably based on OCL constraints in UML metamodel) + // and we do not know these + "templateParameter", "ownedTemplateSignature", "owningTemplateParameter", // would require extra constraints + unused in case study + + "annotatedElement" // behaves like containment|container, but is not one +/**/ + ); + + private List getFeatures(EClass eClass) { + List ret = featuresByEClass.get(eClass); + if(ret == null) { + ret = new ArrayList(); + for(EStructuralFeature feature : eClass.getEAllStructuralFeatures()) { + if(feature.isChangeable() && !feature.isDerived() && !excludedFeatures.contains(feature.getName())) { + ret.add(feature); + } + } + } + return ret; + } + + // and self + private List allContainers(EObject eo) { + List ret = new ArrayList(); + ret.add(eo); + while(eo.eContainer() != null) { + ret.add(eo.eContainer()); + eo = eo.eContainer(); + } + return ret; + } + + private boolean wouldAddContainmentCycle(EObject eo, EStructuralFeature feature, Object newValue_) { + if(feature instanceof EReference) { + EObject newValue = (EObject)newValue_; + EReference ref = (EReference)feature; + if(ref.isContainment() && allContainers(eo).contains(newValue)) { + return true; + } + if(ref.isContainer() && newValue == eo) { + return true; + } + } + return false; + } + + public void performOneChange() { + List allContents = new ArrayList(); + for(Iterator i = modelToFuzz.getAllContents() ; i.hasNext() ; ) { + EObject eo = i.next(); + if(getFeatures(eo.eClass()).size() > 0) { + allContents.add(eo); + } + } + int index = random.nextInt(allContents.size()); + EObject eo = allContents.get(index); + List features = getFeatures(eo.eClass()); + EStructuralFeature feature = features.get(random.nextInt(features.size())); + try { + performOneChange(allContents, eo, feature); + } catch(IllegalArgumentException e) { + // protects against typing constraints that are narrower than actual feature type + String featureName = feature.getName(); + String expectedMessage = "^new" + featureName.substring(0, 1).toUpperCase() + featureName.substring(1) + " must be an instance of .*$"; + if(e.getMessage().matches(expectedMessage)) { + if(logToConsole) { + System.out.println("\t\tFailed because of hidden typing constraint"); + } + } else { + throw e; + } + } + } + + + private void performOneChange(List allContents, EObject eo, EStructuralFeature feature) { + if(feature.isMany()) { + EList value = (EList)eo.eGet(feature); + int n = value.size(); + ManyChangeKind kind = ManyChangeKind.values()[random.nextInt(ManyChangeKind.values().length)]; + trace(eo, feature, kind, value); + switch(kind) { + case ADD: + Object newValue = getPossibleValue(feature, allContents); + if(logToConsole) { + System.out.println("\t\tnewValue = " + toString(newValue)); + } + if(newValue == null) { + if(logToConsole) { + System.out.println("\t\tINVALID (because no possible value):"); + } + } else if(feature.isUnique() && value.contains(newValue)) { + if(logToConsole) { + System.out.println("\t\tINVALID (because already in set):"); + } + } else if(wouldAddContainmentCycle(eo, feature, newValue)) { + if(logToConsole) { + System.out.println("\t\tINVALID (because would add containment cycle):"); + } + } else { + int index; + value.add(index = random.nextInt(n + 1), newValue); + if(undo) { + value.remove(index); + undo = false; + } + } + break; + case REMOVE: + if(n > 0) { + Object oldValue; + int index; + oldValue = value.remove(index = random.nextInt(n)); + if(undo) { + value.add(index, oldValue); + undo = false; + } + } else { + value.clear(); + if(logToConsole) { + System.out.println("\t\tCONVERTED to clear (because of empty collection):"); + } + if(undo) { + undo = false; + } + } + break; +// case CLEAR: +// value.clear(); +// break; + case MOVE: + if(n > 0) { + int newIndex, oldIndex; + value.move(newIndex = random.nextInt(n), oldIndex = random.nextInt(n)); + if(undo) { + value.move(oldIndex, newIndex); + undo = false; + } + } else { + if(logToConsole) { + System.out.println("\t\tINVALID (because of empty collection):"); + } + } + break; + case SET: + newValue = getPossibleValue(feature, allContents); + if(logToConsole) { + System.out.println("\t\tnewValue = " + toString(newValue)); + } + if(newValue == null) { + if(logToConsole) { + System.out.println("\t\tINVALID (because no possible value):"); + } + } else if(feature.isUnique() && value.contains(newValue)) { + if(logToConsole) { + System.out.println("\t\tINVALID (because already in set):"); // TODO: unless we replace that one + } + } else if(wouldAddContainmentCycle(eo, feature, newValue)) { + if(logToConsole) { + System.out.println("\t\tINVALID (because would add containment cycle):"); + } + } else if(value.size() == 0) { + if(logToConsole) { + System.out.println("\t\tINVALID (because empty collection => nothing to replace):"); + } + } else { + int index; + Object oldValue = value.set(index = random.nextInt(n), newValue); + if(undo) { + value.set(index, oldValue); + undo = false; + } + } + break; + default: + throw new UnsupportedOperationException("TODO: add support for " + kind); + } + if(undo) { + System.out.println("Undo many not supported yet"); + undo = false; + } + } else { + SingleChangeKind kind = SingleChangeKind.values()[random.nextInt(SingleChangeKind.values().length)]; + trace(eo, feature, kind, eo.eGet(feature)); + Object oldValue = eo.eGet(feature); + switch(kind) { + case SET: + Object newValue = getPossibleValue(feature, allContents); + if(logToConsole) { + System.out.println("\t\tnewValue = " + toString(newValue)); + } + if(wouldAddContainmentCycle(eo, feature, newValue)) { + if(logToConsole) { + System.out.println("\t\tINVALID (because would add containment cycle):"); + } +/* + } else if(feature.equals(UMLPackage.eINSTANCE.getProfileApplication_AppliedProfile())) { + if(logToConsole) { + System.out.println("\t\tINVALID (because UML does not support this):"); + } +*/ + } else { + if(feature.getName().startsWith("base_")) { + // TODO: handle this more generically + // stereotypes must be unset then set because of the way PapyrusStereotypeListener works + // (i.e., it does not "notify the old value") + eo.eUnset(feature); + } + eo.eSet(feature, newValue); + } + break; + case SET_NULL: + Class instanceClass = feature.getEType().getInstanceClass(); + if(instanceClass != null && instanceClass.isPrimitive()) { + eo.eUnset(feature); + if(logToConsole) { + System.out.println("\t\tCONVERTED to UNSET (because of primitive type):"); + } + } else { + eo.eSet(feature, null); + } + break; + case UNSET: + eo.eUnset(feature); + break; + default: + throw new UnsupportedOperationException("TODO: add support for " + kind); + } + if(undo) { + eo.eSet(feature, oldValue); + undo = false; + } + } + if(undo) { + throw new IllegalStateException("undo should have been performed and disabled"); + } + } + + private void trace(EObject eo, EStructuralFeature feature, Enum kind, Object value) { + if(logToConsole) { + System.out.println("\t" + toString(eo) + "." + feature.getName() + ": " + kind + " (oldValue: " + toString(value) + ")"); + } + } + + + private static Object toString(Object o) { + // Inspect may provide custom output, but it is now commented out to avoid this class depending on it. + // return Inspect.toString(o, null); + return o; + } +} + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..acfa413 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/7.6/userguide/multi_project_builds.html + */ + +rootProject.name = 'EMFModelFuzzer' +include('lib')