From 897129ee2108c13fb23209b7fac8f044cfa745b0 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 19 Feb 2022 13:26:00 +0100 Subject: [PATCH 001/225] creating a test framework for the preprocessing Java pipeline --- key/key.java/build.gradle | 11 + .../pipelineTests/simple/input/Test.java | 14 + .../de/uka/ilkd/key/java/JavaService.java | 86 +++ .../ConstantExpressionEvaluator.java | 49 ++ .../transformations/EvaluationException.java | 13 + .../java/transformations/KeyJavaPipeline.java | 65 ++ .../ClassInitializeMethodBuilder.java | 342 +++++++++ .../ClassPreparationMethodBuilder.java | 150 ++++ .../ConstantStringExpressionEvaluator.java | 60 ++ .../ConstructorNormalformBuilder.java | 245 +++++++ .../pipeline/CreateBuilder.java | 97 +++ .../pipeline/CreateObjectBuilder.java | 118 +++ .../pipeline/ImplicitFieldAdder.java | 178 +++++ .../InstanceAllocationMethodBuilder.java | 54 ++ .../pipeline/JMLTransformer.java | 686 ++++++++++++++++++ .../pipeline/JavaTransformer.java | 127 ++++ .../pipeline/LocalClassTransformation.java | 52 ++ .../pipeline/PipelineConstants.java | 25 + .../pipeline/PrepareObjectBuilder.java | 152 ++++ .../TransformationPipelineServices.java | 442 +++++++++++ .../pipeline/TransformerCache.java | 9 + .../src/test/java/KeyJavaPipelineTest.java | 84 +++ key/settings.gradle | 2 + 23 files changed, 3061 insertions(+) create mode 100644 key/key.java/build.gradle create mode 100644 key/key.java/pipelineTests/simple/input/Test.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/ConstantExpressionEvaluator.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/EvaluationException.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/KeyJavaPipeline.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstantStringExpressionEvaluator.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstructorNormalformBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ImplicitFieldAdder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/InstanceAllocationMethodBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JMLTransformer.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JavaTransformer.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/LocalClassTransformation.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PrepareObjectBuilder.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformationPipelineServices.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformerCache.java create mode 100644 key/key.java/src/test/java/KeyJavaPipelineTest.java diff --git a/key/key.java/build.gradle b/key/key.java/build.gradle new file mode 100644 index 00000000000..d685bd423d2 --- /dev/null +++ b/key/key.java/build.gradle @@ -0,0 +1,11 @@ +plugins {} + +dependencies { + api project(':key.util') + api project(':key.core') + + api 'com.github.javaparser:javaparser-core:3.23.2-SNAPSHOT' + api 'com.github.javaparser:javaparser-core-serialization:3.23.2-SNAPSHOT' + api 'com.github.javaparser:javaparser-symbol-solver-core:3.23.2-SNAPSHOT' + +} \ No newline at end of file diff --git a/key/key.java/pipelineTests/simple/input/Test.java b/key/key.java/pipelineTests/simple/input/Test.java new file mode 100644 index 00000000000..afdb0812a2e --- /dev/null +++ b/key/key.java/pipelineTests/simple/input/Test.java @@ -0,0 +1,14 @@ +public class Test { + public static int abc; + static { + abc = 2; + } + + public int memberVar; + { memberVar = 42; } +} + +public class SubClass extends Test { + public int memberVar; + { memberVar = 41; } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java new file mode 100644 index 00000000000..627d7c0ec7d --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java @@ -0,0 +1,86 @@ +package de.uka.ilkd.key.java; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.resolution.SymbolResolver; +import com.github.javaparser.symbolsolver.JavaSymbolSolver; +import com.github.javaparser.symbolsolver.model.resolution.TypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ClassLoaderTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import recoder.util.Debug; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author Alexander Weigl + * @version 1 (19.02.22) + */ +public class JavaService { + private static final Logger LOGGER = LoggerFactory.getLogger(JavaService.class); + + @Nonnull + private final List sourcePaths; + @Nullable + private ParserConfiguration config; + @Nullable + private TypeSolver typeSolver; + + @Nullable + private SymbolResolver symbolResolver; + + public JavaService(Collection sourcePaths) { + this.sourcePaths = new ArrayList<>(sourcePaths); + } + + public JavaParser createJavaParser() { + return new JavaParser(getConfiguration()); + } + + @Nonnull + private ParserConfiguration getConfiguration() { + if (config == null) { + config = new ParserConfiguration(); + config.setSymbolResolver(getSymbolResolver()); + } + return config; + } + + @Nonnull + private SymbolResolver getSymbolResolver() { + if (symbolResolver == null) { + symbolResolver = new JavaSymbolSolver(getTypeSolver()); + } + return symbolResolver; + } + + + public TypeSolver getTypeSolver() { + if (typeSolver == null) { + var ct = new CombinedTypeSolver(); + for (File sourcePath : sourcePaths) { + if (sourcePath.isFile() && sourcePath.getName().endsWith(".jar")) { + try { + ct.add(new JarTypeSolver(sourcePath)); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } + } else if (sourcePath.isDirectory()) { + ct.add(new JavaParserTypeSolver(sourcePath, config)); + } + } + ct.add(new ClassLoaderTypeSolver(ClassLoader.getSystemClassLoader())); + typeSolver = ct; + } + return typeSolver; + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/ConstantExpressionEvaluator.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/ConstantExpressionEvaluator.java new file mode 100644 index 00000000000..336e75a0ac9 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/ConstantExpressionEvaluator.java @@ -0,0 +1,49 @@ +package de.uka.ilkd.key.java.transformations; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.Expression; +import jdk.jshell.JShell; +import jdk.jshell.SnippetEvent; + +import java.util.List; + +/** + * @author Alexander Weigl + * @version 1 (11/2/21) + */ +public class ConstantExpressionEvaluator { + private final JavaParser javaParser; + private final JShell jShell = JShell.create(); + + public ConstantExpressionEvaluator(JavaParser javaParser) { + this.javaParser = javaParser; + } + + public boolean isCompileTimeConstant(Expression expr) throws EvaluationException { + List value = jShell.eval(expr.toString()); + assert value.size() == 1; + SnippetEvent evt = value.get(0); + //throw new EvaluationException("Could not evaluate " + expr, evt.exception()); + return evt.exception() == null; + //String result = evt.value(); + } + + public Expression evaluate(Expression expression) throws EvaluationException { + return evaluate(expression.toString()); + } + + public Expression evaluate(String expression) throws EvaluationException { + List value = jShell.eval(expression); + assert value.size() == 1; + SnippetEvent evt = value.get(0); + if (evt.exception() != null) { + throw new EvaluationException("Could not evaluate " + expression, evt.exception()); + } + return javaParser.parseExpression(evt.value()).getResult().orElseThrow( + () -> new EvaluationException("Could not evaluate " + expression, evt.exception())); + } + + /*public Expression evaluate(de.uka.ilkd.key.java. expr) throws EvaluationException { + return evaluate(expr.toString()); + }*/ +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/EvaluationException.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/EvaluationException.java new file mode 100644 index 00000000000..58ecab3c2ba --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/EvaluationException.java @@ -0,0 +1,13 @@ +package de.uka.ilkd.key.java.transformations; + +import jdk.jshell.JShellException; + +/** + * @author Alexander Weigl + * @version 1 (11/2/21) + */ +public class EvaluationException extends Exception { + public EvaluationException(String message, Exception exception) { + super(message, exception); + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/KeyJavaPipeline.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/KeyJavaPipeline.java new file mode 100644 index 00000000000..ac1f56dd156 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/KeyJavaPipeline.java @@ -0,0 +1,65 @@ +package de.uka.ilkd.key.java.transformations; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.TypeDeclaration; +import de.uka.ilkd.key.java.transformations.pipeline.*; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * @author Alexander Weigl + * @version 1 (11/7/21) + */ +public class KeyJavaPipeline { + private final TransformationPipelineServices pipelineServices; + private final List steps = new LinkedList<>(); + + public KeyJavaPipeline(TransformationPipelineServices pipelineServices) { + this.pipelineServices = pipelineServices; + } + + public TransformationPipelineServices getPipelineServices() { + return pipelineServices; + } + + public List getSteps() { + return steps; + } + + public static KeyJavaPipeline createDefault(TransformationPipelineServices pipelineServices) { + KeyJavaPipeline p = new KeyJavaPipeline(pipelineServices); + //new EnumClassBuilder(pipelineServices), + p.add(new JMLTransformer(pipelineServices)); + p.add(new ImplicitFieldAdder(pipelineServices)); + p.add(new InstanceAllocationMethodBuilder(pipelineServices)); + p.add(new ConstructorNormalformBuilder(pipelineServices)); + p.add(new ClassPreparationMethodBuilder(pipelineServices)); + p.add(new ClassInitializeMethodBuilder(pipelineServices)); + p.add(new PrepareObjectBuilder(pipelineServices)); + p.add(new CreateBuilder(pipelineServices)); + p.add(new CreateObjectBuilder(pipelineServices)); + p.add(new LocalClassTransformation(pipelineServices)); + p.add(new ConstantStringExpressionEvaluator(pipelineServices)); + return p; + } + + public void add(JavaTransformer step) { + steps.add(step); + } + + public void apply() { + apply(pipelineServices.getCache().getUnits()); + } + + public void apply(Collection compilationUnits) { + for (JavaTransformer step : steps) { + for (CompilationUnit compilationUnit : compilationUnits) { + for (TypeDeclaration type : compilationUnit.getTypes()) { + step.apply(type); + } + } + } + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java new file mode 100644 index 00000000000..5da1c3ef4ad --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java @@ -0,0 +1,342 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.key.KeyPassiveExpression; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.VoidType; +import de.uka.ilkd.key.java.transformations.ConstantExpressionEvaluator; +import de.uka.ilkd.key.java.transformations.EvaluationException; + +import java.util.Optional; + +import static de.uka.ilkd.key.java.transformations.pipeline.ClassPreparationMethodBuilder.CLASS_PREPARE_IDENTIFIER; + +/** + * Each class is prepared before it is initialised. The preparation of + * a class consists of pre-initialising the class fields with their + * default values. This class creates the implicit method + * <clprepare> responsible for the class + * preparation. + */ +public class ClassInitializeMethodBuilder extends JavaTransformer { + public static final String CLASS_INITIALIZE_IDENTIFIER = ""; + + /** + * Creates an instance of the class preparation method model + * transformer. Information about the current recoder model can be + * accessed via the given service configuration. The implicit + * preparation method is created and added for all classes, + * which are declared in one of the given compilation units. + * + * @param services the CrossReferenceServiceConfiguration with the + * information about the recoder model + */ + public ClassInitializeMethodBuilder(TransformationPipelineServices services) { + super(services); + } + + /** + * returns true if the given fieldspecification denotes a constant + * field. A constant field is declared as final and static and + * initialised with a time constant, which is not prepared or + * initialised here. ATTENTION: this is a derivation from the JLS + * but the obtained behaviour is equivalent as we only consider + * completely compiled programs and not partial compilations. The + * reason for preparation and initialisation of comnpile time + * constant fields is due to binary compatibility reasons. + */ + private boolean isConstantField(FieldDeclaration spec, VariableDeclarator decl) { + boolean result = spec.isStatic() && spec.isFinal(); + if (!result) { + return false; + } + ConstantExpressionEvaluator ce = services.getConstantEvaluator(); + + try { + Optional init = decl.getInitializer(); + if (init.isPresent()) { + return ce.isCompileTimeConstant(init.get()); + } else { + return false; + } + } catch (NumberFormatException | ArithmeticException | EvaluationException e) { + result = false; + } + return result; + } + + /** + * creates the package reference java.lang + */ + private ClassOrInterfaceType createJavaLangPackageReference() { + return new ClassOrInterfaceType(new ClassOrInterfaceType(null, "java"), "lang"); + } + + + /** + * iterates through the given field declaration and creates for each + * specification that contains an initializer a corresponding copy + * assignment. Thereby only non constant fields are considered. + */ + private NodeList fieldInitializersToAssignments(FieldDeclaration fd) { + NodeList specs = fd.getVariables(); + NodeList result = new NodeList<>(); + for (VariableDeclarator fs : specs) { + if (fd.isStatic() && fs.getInitializer().isPresent() && !isConstantField(fd, fs)) { + result.add( + new ExpressionStmt( + new AssignExpr( + new KeyPassiveExpression(new NameExpr(fs.getName())), + fs.getInitializer().get().clone(), + AssignExpr.Operator.ASSIGN + + ))); + } + } + return result; + + } + + + /** + * retrieves all static non constant fields and returns a list of + * copy assignment pre-initialising them with their default values + *

+ * some special settings for implicit fields are performed here as well + * + * @param typeDeclaration the TypeDeclaration whose fields have to be prepared + * @return the list of copy assignments + */ + private NodeList getInitializers(TypeDeclaration typeDeclaration) { + NodeList result = new NodeList<>(); + for (Node childNode : typeDeclaration.getChildNodes()) { + if (childNode instanceof ConstructorDeclaration) { + result.add(((ConstructorDeclaration) childNode).getBody().clone()); + } else if (childNode instanceof FieldDeclaration) { + result.addAll(fieldInitializersToAssignments((FieldDeclaration) childNode)); + } + } + return result; + } + + /** + * creates the following catch clause + *

+     * catch (caughtType caughtParam) {
+     * <classInitializationInProgress>=false;
+     * <classClassErroneous>=true;
+     * t;
+     * }
+ * + */ + private CatchClause createCatchClause(String caughtType, String caughtParam, ThrowStmt t) { + NodeList catcher = new NodeList(); + var resetInitInProgress = + assign(new KeyPassiveExpression( + new NameExpr(new SimpleName(PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS))), + new BooleanLiteralExpr(false)); + + var markErroneous = + assign(new KeyPassiveExpression( + new NameExpr(new SimpleName(PipelineConstants.IMPLICIT_CLASS_ERRONEOUS))), + new BooleanLiteralExpr(true)); + + Parameter param = new Parameter( + services.getType("java", "lang", caughtType), + caughtParam); + + catcher.add(resetInitInProgress); + catcher.add(markErroneous); + + catcher.add(t); + + return new CatchClause(param, new BlockStmt(catcher)); + } + + + /** + * around the initializers there is a try block that catches + * eventually thrown errors or exceptions and handles them in a + * special way + */ + private TryStmt createInitializerExecutionTryBlock(TypeDeclaration td) { + // try block + NodeList initializerExecutionBody = getInitializers(td); + if (initializerExecutionBody == null && initializerExecutionBody.isNonEmpty()) { + initializerExecutionBody = new NodeList<>(); + } + + if (td instanceof ClassOrInterfaceDeclaration && !td.resolve().isJavaLangObject()) { + var cd = (ClassOrInterfaceDeclaration) td; + final var superType = cd.getExtendedTypes(0); + final var scope = new NameExpr(superType.getName()); //TODO convert fqn + initializerExecutionBody.add(0, + new ExpressionStmt( + new KeyPassiveExpression( + new MethodCallExpr(scope, CLASS_INITIALIZE_IDENTIFIER)))); + } + + // catch clauses + var catchClauses = new NodeList(); + catchClauses.add( + createCatchClause("Error", "err", + new ThrowStmt(new NameExpr(new SimpleName("err"))))); + + var exceptionInInitializerArguments = new NodeList(); + exceptionInInitializerArguments.add(new NameExpr(new SimpleName("twa"))); + + ThrowStmt t = new ThrowStmt( + new ObjectCreationExpr(null, + services.getType("java", "lang", "ExceptionInInitializerError"), + exceptionInInitializerArguments)); + + catchClauses.add(createCatchClause("Throwable", "twa", t)); + + return new TryStmt(new BlockStmt(initializerExecutionBody), catchClauses, null); + } + + + /** + * creates the body of the initialize method + */ + private BlockStmt createInitializeMethodBody(TypeDeclaration td) { + + var methodBody = new NodeList(); + var clInitializeBody = new NodeList(); + var clInitNotInProgressBody = new NodeList(); + + var clNotPreparedBody = new NodeList(); + clNotPreparedBody.add( + new ExpressionStmt( + new KeyPassiveExpression( + new MethodCallExpr(CLASS_PREPARE_IDENTIFIER)))); + + + IfStmt isClassPrepared = new IfStmt( + new UnaryExpr( + new KeyPassiveExpression( + new FieldAccessExpr(new ThisExpr(), + PipelineConstants.IMPLICIT_CLASS_PREPARED)), + UnaryExpr.Operator.LOGICAL_COMPLEMENT), + new BlockStmt(clNotPreparedBody), + null); + + + clInitNotInProgressBody.add(isClassPrepared); + + + var clErroneousBody = new NodeList(); + clErroneousBody.add( + new ThrowStmt( + new ObjectCreationExpr(null, + services.getType("java", "lang", "NoClassDefFoundError"), + new NodeList<>()))); + + // IF : clErroneousBody : null + IfStmt isClassErroneous = new IfStmt( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_ERRONEOUS)), + new BlockStmt(clErroneousBody), + null); + + clInitNotInProgressBody.add(isClassErroneous); + + + // @(CLASS_INIT_IN_PROGRESS) = true + clInitNotInProgressBody.add(assign( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS)), + new BooleanLiteralExpr(true))); + + + // create try block in initialize method + clInitNotInProgressBody.add(createInitializerExecutionTryBlock(td)); + clInitNotInProgressBody.add( + assign( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS)), + new BooleanLiteralExpr(false))); + clInitNotInProgressBody.add( + assign( + new KeyPassiveExpression(( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_ERRONEOUS))), + new BooleanLiteralExpr(false))); + clInitNotInProgressBody.add( + assign( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_INITIALIZED)), + new BooleanLiteralExpr(true))); + + + IfStmt isClassInitializationInProgress = new IfStmt( + new UnaryExpr( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS)), + UnaryExpr.Operator.LOGICAL_COMPLEMENT), + new BlockStmt(clInitNotInProgressBody), + null); + + + clInitializeBody.add(isClassInitializationInProgress); + IfStmt isClassInitialized = new IfStmt( + new UnaryExpr( + new KeyPassiveExpression( + new NameExpr(PipelineConstants.IMPLICIT_CLASS_INITIALIZED)), + UnaryExpr.Operator.LOGICAL_COMPLEMENT), + new BlockStmt(clInitializeBody), + null); + + + methodBody.add(isClassInitialized); + + return new BlockStmt(methodBody); + } + + + /** + * creates the static method <clprepare> for the + * given type declaration + * + * @param td the TypeDeclaration to which the new created method + * will be attached + * @return the created class preparation method + */ + private MethodDeclaration createInitializeMethod(TypeDeclaration td) { + NodeList modifiers = new NodeList(); + modifiers.add(new Modifier(Modifier.Keyword.STATIC)); + modifiers.add(new Modifier(Modifier.Keyword.PUBLIC)); + MethodDeclaration md = new MethodDeclaration(modifiers, + new VoidType(), + CLASS_INITIALIZE_IDENTIFIER); + md.setBody(createInitializeMethodBody(td)); + return md; + } + + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + td.addMember(createInitializeMethod(td)); + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java new file mode 100644 index 00000000000..fa7e0750ffe --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java @@ -0,0 +1,150 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.AssignExpr; +import com.github.javaparser.ast.expr.BooleanLiteralExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.key.KeyPassiveExpression; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.VoidType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * Each class is prepared before it is initialised. The preparation of + * a class consists of pre-initialising the class fields with their + * default values. This class creates the implicit method + * <clprepare> responsible for the class + * preparation. + */ +public class ClassPreparationMethodBuilder extends JavaTransformer { + private static final Logger LOGGER = LoggerFactory.getLogger(ClassPreparationMethodBuilder.class); + + public static final String CLASS_PREPARE_IDENTIFIER = ""; + + /** + * maps a class to its static NON-CONSTANT fields + */ + private final HashMap, NodeList> class2staticFields; + + /** + * Creates an instance of the class preparation method model + * transformer. Information about the current recoder model can be + * accessed via the given service configuration. The implicit + * preparation method is created and added for all classes, + * which are declared in one of the given compilation units. + * + * @param services the CrossReferenceServiceConfiguration with the + * information about the recoder model + */ + public ClassPreparationMethodBuilder(TransformationPipelineServices services) { + super(services); + class2staticFields = new LinkedHashMap<>(1024); + } + + + /** + * retrieves all static non-constant fields and returns a list of + * copy assignment pre-initialising them with their default values + *

+ * some special settings for implicit fields are performed here as well + * + * @param typeDeclaration the TypeDeclaration whose fields have to be prepared + * @return the list of copy assignments + */ + private NodeList prepareFields(TypeDeclaration typeDeclaration) { + NodeList result = new NodeList<>(); + List fields = typeDeclaration.getFields(); + for (FieldDeclaration spec : fields) { + if (spec.isStatic() && spec.isFinal()) { + for (VariableDeclarator variable : spec.getVariables()) { + if (services.isConstant(variable.getInitializer())) { + SimpleName ident = variable.getName(); + result.add( + new ExpressionStmt( + new AssignExpr( + new KeyPassiveExpression( + new NameExpr(ident.clone())), + services.getDefaultValue(variable.getType()), + AssignExpr.Operator.ASSIGN))); + } + } + } + } + + result.add( + new ExpressionStmt( + new AssignExpr( + new KeyPassiveExpression(new NameExpr(PipelineConstants.IMPLICIT_CLASS_PREPARED)), + new BooleanLiteralExpr(true), + AssignExpr.Operator.ASSIGN))); + return result; + } + + public void prepare() { + for (var cu : cache.getUnits()) { + for (var td : cu.getTypes()) { + boolean b = td.getMembers().stream() + .anyMatch(BodyDeclaration::isClassOrInterfaceDeclaration); + + if (b) { + LOGGER.debug("Inner Class detected. Reject building class initialisation methods."); + } + + // collect initializers for transformation phase + class2staticFields.put(td, prepareFields(td)); + } + } + } + + /** + * creates the static method <clprepare> for the + * given type declaration + * + * @param td the TypeDeclaration to which the new created method + * will be attached + * @return the created class preparation method + */ + private MethodDeclaration createPrepareMethod(TypeDeclaration td) { + NodeList modifiers = new NodeList<>( + new Modifier(Modifier.Keyword.STATIC), + new Modifier(Modifier.Keyword.PRIVATE)); + MethodDeclaration method = new MethodDeclaration(modifiers, + new VoidType(), // return type is void + CLASS_PREPARE_IDENTIFIER); + method.setBody(new BlockStmt(class2staticFields.get(td))); + return method; + } + + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + td.addMember(createPrepareMethod(td)); + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstantStringExpressionEvaluator.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstantStringExpressionEvaluator.java new file mode 100644 index 00000000000..04e666a4d39 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstantStringExpressionEvaluator.java @@ -0,0 +1,60 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.visitor.VoidVisitorWithDefaults; +import de.uka.ilkd.key.java.transformations.ConstantExpressionEvaluator; +import de.uka.ilkd.key.java.transformations.EvaluationException; + +import java.util.Objects; + +public class ConstantStringExpressionEvaluator extends JavaTransformer { + + public ConstantStringExpressionEvaluator(TransformationPipelineServices services) { + super(services); + } + + + private void evaluateConstantStringExpressions(Node td) { + td.accept(new VoidVisitorWithDefaults<>() { + @Override + public void defaultAction(Node n, Object arg) { + if (n instanceof Expression) { + var e = (Expression) n; + ConstantExpressionEvaluator cee = services.getConstantEvaluator(); + var expType = e.calculateResolvedType(); + if (!e.isNullLiteralExpr() && expType != null + && expType.isReferenceType() + && Objects.equals(expType.asReferenceType().getQualifiedName(), + "java.lang.String")) { + try { + var expression = cee.evaluate(e); + e.replace(expression); + } catch (EvaluationException t) { + // + } + } + } + } + }, null); + } + + @Override + public void apply(TypeDeclaration td) { + evaluateConstantStringExpressions(td); + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstructorNormalformBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstructorNormalformBuilder.java new file mode 100644 index 00000000000..50fe5d96d18 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ConstructorNormalformBuilder.java @@ -0,0 +1,245 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.ReferenceType; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration; + +import java.util.Optional; +import java.util.stream.Collectors; + +import static de.uka.ilkd.key.java.transformations.pipeline.PipelineConstants.CONSTRUCTOR_NORMALFORM_IDENTIFIER; +import static de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices.cloneList; + +/** + * Transforms the constructors of the given class to their + * normalform. The constructor normalform can then be accessed via a + * methodcall <init>. The visibility of + * the normalform is the same as for the original constructor. + */ +public class ConstructorNormalformBuilder extends JavaTransformer { + /** + * creates the constructor normalform builder + */ + public ConstructorNormalformBuilder(TransformationPipelineServices services) { + super(services); + } + + protected Optional getImplicitEnclosingThis(TypeDeclaration cd) { + return cd.getFieldByName(PipelineConstants.IMPLICIT_ENCLOSING_THIS); + } + + private void attachDefaultConstructor(ClassOrInterfaceDeclaration cd) { + var body = new BlockStmt(); + body.addStatement(new MethodCallExpr(new SuperExpr(), CONSTRUCTOR_NORMALFORM_IDENTIFIER)); + var initializers = services.getInitializers(cd); + int i = 0; + for (Statement initializer : initializers) { + body.addStatement(i++, initializer.clone()); + } + MethodDeclaration def = cd.addMethod(CONSTRUCTOR_NORMALFORM_IDENTIFIER, Modifier.Keyword.PUBLIC); + def.setBody(body); + } + + /** + * Creates the normalform of the given constructor, that is declared + * in class cd. For a detailed description of the normalform to be + * built see the KeY Manual. + * + * @param cd the TypeDeclaration where the cons is declared + * @param cons the Constructor to be transformed + */ + private void normalform(ClassOrInterfaceDeclaration cd, ConstructorDeclaration cons) { + NodeList mods = new NodeList<>(); + var et = getImplicitEnclosingThis(cd); + var td = getEnclosingClass(cd).get(); + var outerVars = services.getFinalVariables(cd); + int j = !et.isPresent() ? 0 : 1; + if (outerVars != null) j += outerVars.size(); + Parameter pd = null; + AssignExpr ca = null; + String etId = "_ENCLOSING_THIS"; + if (et.isPresent()) { + pd = new Parameter( + new ClassOrInterfaceType(null, td.getName().getIdentifier()), + etId); + ca = new AssignExpr( + new FieldAccessExpr(new ThisExpr(), et.get().getVariables().get(0).getName().getIdentifier()), + new NameExpr(etId), AssignExpr.Operator.ASSIGN); + } + + BlockStmt body; + NodeList recThrows; + NodeList parameters; + if (!(cons instanceof ConstructorDeclaration)) { + mods.add(new Modifier(Modifier.Keyword.PUBLIC)); + parameters = new NodeList<>(); + recThrows = null; + body = new BlockStmt(); + } else { + mods = cloneList(cons.getModifiers()); + parameters = cloneList(cons.getParameters()); + recThrows = cloneList(cons.getThrownExceptions()); + + BlockStmt origBody = cons.getBody(); + if (origBody == null) // may happen if a stub is defined with an empty constructor + body = null; + else + body = origBody.clone(); + } + + if (outerVars != null && !outerVars.isEmpty()) { + if (parameters.isEmpty()) { + attachDefaultConstructor(cd); + } + + for (var v : outerVars) { + parameters.add(new Parameter(services.getType(v.getType()), v.getName())); + } + } + + if (pd != null) { + if (parameters.isEmpty()) { + attachDefaultConstructor(cd); + } + parameters.add(pd); + } + + if (cd.resolve().isJavaLangObject() && body != null) { + // remember original first statement + Statement first = !body.getStatements().isEmpty() ? body.getStatement(0) : null; + + // first statement has to be a this or super constructor call + if (!(first instanceof ExplicitConstructorInvocationStmt)) { + body.addStatement(0, new MethodCallExpr(new SuperExpr(), CONSTRUCTOR_NORMALFORM_IDENTIFIER)); + } else { + body.getStatements().remove(0); + var constructorCall = (ExplicitConstructorInvocationStmt) first; + if (constructorCall.isThis()) { + var methodCall = new MethodCallExpr(new ThisExpr(), + constructorCall.getTypeArguments().orElse(null), //copy? + CONSTRUCTOR_NORMALFORM_IDENTIFIER, + constructorCall.getArguments() /*copy?*/); + body.addStatement(0, methodCall); + } else { + NodeList args = constructorCall.getArguments(); + if (constructorCall.getExpression().isPresent()) { + if (args == null) args = new NodeList<>(); + args.add((constructorCall.getExpression().get())); + } else if (!cd.resolve().getAllAncestors().isEmpty()) { + if (args == null) args = new NodeList<>(); + args.add(new NameExpr(etId)); + } + var expr = new MethodCallExpr(new SuperExpr(), + null, + CONSTRUCTOR_NORMALFORM_IDENTIFIER, + args); + body.addStatement(0, expr); + } + } + + // if the first statement is not a this constructor reference + // the instance initializers have to be added in source code + // order + if (!(first instanceof ExplicitConstructorInvocationStmt)) { + NodeList initializers = services.getInitializers(cd); + if (ca != null) { + body.addStatement(0, ca); + } + + int i = 0; + for (ResolvedFieldDeclaration outerVar : outerVars) { + final var fieldAccessExpr = new FieldAccessExpr(new ThisExpr(), + PipelineConstants.FINAL_VAR_PREFIX + outerVar.getName()); + var assign = new AssignExpr(fieldAccessExpr, new NameExpr(outerVar.getName()), + AssignExpr.Operator.ASSIGN); + body.addStatement((ca != null ? 1 : 0) + (i++), assign); + } + + for (i = 0; i < initializers.size(); i++) { + body.addStatement(i + j + 1, initializers.get(i).clone()); + } + } + } + + MethodDeclaration nf = new MethodDeclaration( + mods, + new VoidType(), + CONSTRUCTOR_NORMALFORM_IDENTIFIER); + nf.setParameters(parameters); + nf.setThrownExceptions(recThrows); + nf.setBody(body); + cd.addMember(nf); + } + + private Optional getEnclosingClass(ClassOrInterfaceDeclaration cd) { + if (cd.isNestedType()) { + return cd.getParentNode().map(ClassOrInterfaceDeclaration.class::cast); + } + return Optional.empty(); + } + + private ConstructorDeclaration attachConstructorDecl(TypeDeclaration td) { + if (td.getParentNode().get() instanceof ObjectCreationExpr) { + var n = (ObjectCreationExpr) td.getParentNode().get(); + final var args = n.getArguments(); + if (args == null || args.size() == 0) return null; + + var type = n.getType().resolve(); + var constr = n.resolve().toAst().get(); + constr = constr.clone(); + final NodeList cargs = new NodeList<>(args.stream().map(Expression::clone).collect(Collectors.toList())); + var sr = new MethodCallExpr(null, new NodeList<>(), new SimpleName("super"), cargs); + constr.setBody(new BlockStmt(new NodeList<>(new ExpressionStmt(sr)))); + td.addMember(constr); + return constr; + } + return null; + } + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + if (td instanceof ClassOrInterfaceDeclaration) { + var cd = (ClassOrInterfaceDeclaration) td; + var constructors = td.getConstructors(); + ConstructorDeclaration anonConstr = null; + if (cd.getName() == null) { + anonConstr = attachConstructorDecl(td); + } + if (anonConstr != null) constructors.add(anonConstr); + for (ConstructorDeclaration constructor : constructors) { + normalform(cd, constructor); + } + + var mdl = td.getMethods(); + for (MethodDeclaration md : mdl) { + cd.addMember(md); + } + } + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java new file mode 100644 index 00000000000..6b5606c237e --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java @@ -0,0 +1,97 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.BooleanLiteralExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.ThisExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; + +/** + * If an allocation expression new Class(...) occurs, a new object + * has to be created, in KeY this is quite similar to take it out of a list of + * objects and setting the implicit flag <created> to + * true as well as setting all fields of the object to their + * default values. For the complete procedure, the method creates the + * implicit method <createObject$gt; which on its part calls + * another implicit method lt;prepare> for setting the fields + * default values. + */ +public class CreateBuilder extends JavaTransformer { + + public static final String IMPLICIT_CREATE = ""; + + public CreateBuilder(TransformationPipelineServices services) { + super(services); + } + + /** + * Creates the body of the static <createObject> + * method. + */ + private BlockStmt createBody() { + NodeList result = new NodeList<>(); + result.add(assign(attribute(new ThisExpr(), PipelineConstants.IMPLICIT_INITIALIZED), + new BooleanLiteralExpr(false))); + + result.add( + new ExpressionStmt( + new MethodCallExpr(PipelineConstants.IMPLICIT_OBJECT_PREPARE_ENTER))); + + result.add(new ReturnStmt(new ThisExpr())); + + return new BlockStmt(result); + + } + + + /** + * creates the implicit static <createObject> + * method that takes the object to be created out of the pool + * + * @param type the TypeDeclaration for which the + * <prepare> is created + * @return the implicit <prepare> method + */ + public MethodDeclaration createMethod(TypeDeclaration type) { + NodeList modifiers = new NodeList<>(); + modifiers.add(new Modifier(Modifier.Keyword.PUBLIC)); + + MethodDeclaration md = new MethodDeclaration( + modifiers, new ClassOrInterfaceType(null, services.getId(type)), + IMPLICIT_CREATE); + md.setBody(createBody()); + return md; + } + + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + td.addMember(createMethod(td)); + } + + +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java new file mode 100644 index 00000000000..73307471493 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java @@ -0,0 +1,118 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.key.KeyMethodBodyStatement; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.type.ClassOrInterfaceType; + +import java.util.HashMap; +import java.util.LinkedHashMap; + +/** + * If an allocation expression new Class(...) occurs, a new object + * has to be created, in KeY this is quite similar to take it out of a list of + * objects and setting the implicit flag <created> to + * true as well as setting all fields of the object to their + * default values. For the complete procedure, the method creates the + * implicit method <createObject$gt; which on its part calls + * another implicit method lt;prepare> for setting the fields + * default values. + */ +public class CreateObjectBuilder extends JavaTransformer { + + public static final String IMPLICIT_OBJECT_CREATE = ""; + public static final String NEW_OBJECT_VAR_NAME = "__NEW__"; + private final HashMap, SimpleName> class2SimpleName; + + + public CreateObjectBuilder(TransformationPipelineServices services) { + super(services); + class2SimpleName = new LinkedHashMap<>(); + } + + + /** + * Creates the body of the static <createObject> + * method. + */ + private BlockStmt createBody(ClassOrInterfaceDeclaration recoderClass) { + var result = new BlockStmt(); + final var thisType = services.getType(recoderClass); + var local = new VariableDeclarationExpr(thisType, NEW_OBJECT_VAR_NAME); + result.addStatement(local); + + var arguments = new NodeList(); + + result.addStatement( + assign(new NameExpr(NEW_OBJECT_VAR_NAME), + new MethodCallExpr( + new TypeExpr(thisType), + PipelineConstants.IMPLICIT_INSTANCE_ALLOCATE, + arguments))); + + MethodCallExpr createRef = new MethodCallExpr(new NameExpr(NEW_OBJECT_VAR_NAME), CreateBuilder.IMPLICIT_CREATE); + + // July 08 - mulbrich: wraps createRef into a method body statement to + // avoid unnecessary dynamic dispatch. + // Method body statement are not possible for anonymous classes, however. + // Use a method call there + if (recoderClass.getName() == null) {//TODO weigl recheck + // anonymous + result.addStatement( + new MethodCallExpr(new NameExpr(new SimpleName(NEW_OBJECT_VAR_NAME)), CreateBuilder.IMPLICIT_CREATE)); + } else { + result.addStatement(new KeyMethodBodyStatement(null, createRef, thisType)); + } + + // TODO why does the method return a value? Is the result ever used?? + result.addStatement(new ReturnStmt(new NameExpr(NEW_OBJECT_VAR_NAME))); + return result; + } + + + /** + * appends and creates the implicit static <createObject> + * method that takes the object to be created out of the pool + */ + public void createMethod(ClassOrInterfaceDeclaration type) { + var md = type.addMethod( + IMPLICIT_OBJECT_CREATE, + Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC); + md.setType(new ClassOrInterfaceType(null, type.getName(), null)); + md.setBody(createBody(type)); + } + + public void prepare() { + } + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + if (td instanceof ClassOrInterfaceDeclaration) { + createMethod((ClassOrInterfaceDeclaration) td); + } + } + + +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ImplicitFieldAdder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ImplicitFieldAdder.java new file mode 100644 index 00000000000..c1cd917efdd --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ImplicitFieldAdder.java @@ -0,0 +1,178 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.ast.type.Type; + + +/** + * The Java DL requires some implicit fields and methods, that are + * available in each Java class. The name of the implicit fields/methods + * is usually enclosed between two angle brackets. To access them in a + * uniform way, they are added as usual fields to the classes, in + * particular this makes it possible to parse them in a natural way. + * The ImplicitFieldAdder is responsible to add all implicit fields to + * the type declarations of the model. As the implicit methods and only + * them will access these fields, this transformer has to be executed + * before the other transformers are called. + */ +public class ImplicitFieldAdder extends JavaTransformer { + + /** + * flag set if java.lang.Object has been already transformed + */ + private boolean transformedObject = false; + + /** + * creates a transformation that adds all implicit fields, + * for example <created>, + * <initialized> and + * <nextToCreate> etc. + * + * @param services the CrossReferenceServiceConfiguration to access + * model information + */ + public ImplicitFieldAdder(TransformationPipelineServices services) { + super(services); + } + + /** + * creates an implicit field of the given type and name + * + * @param typeName the name of the type of the new field to create + * @param fieldName the name of the field + * @param isStatic a boolean that is true if the field has to be + * created as static (class) field + * @return the new created field declaration + */ + public static FieldDeclaration createImplicitRecoderField( + Type typeName, String fieldName, boolean isStatic, boolean isPrivate) { + return createImplicitRecoderField(typeName, fieldName, isStatic, isPrivate, false); + } + + public static FieldDeclaration createImplicitRecoderField( + Type type, String fieldName, boolean isStatic, boolean isPrivate, boolean isFinal) { + NodeList modifiers = new NodeList<>(); + if (isStatic) { + modifiers.add(new Modifier(Modifier.Keyword.STATIC)); + } + if (isPrivate) { + modifiers.add(new Modifier(Modifier.Keyword.PRIVATE)); + } else { + modifiers.add(new Modifier(Modifier.Keyword.PUBLIC)); + } + + if (isFinal) { + modifiers.add(new Modifier(Modifier.Keyword.FINAL)); + } + + VariableDeclarator variable = new VariableDeclarator(type, fieldName); + FieldDeclaration fd = new FieldDeclaration(modifiers, variable); + fd.addAnnotation("javax.annotation.processing.Generated"); + return fd; + } + + + /** + * The implicit fields divide up into two categories. Global fields + * declared just in java.lang.Object and type specific one declared + * in each reference type. This method adds the global ones. + */ + private void addGlobalImplicitRecoderFields(TypeDeclaration td) { + // instance + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_INITIALIZED, false, false)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CREATED, false, false)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.INT), + PipelineConstants.IMPLICIT_TRANSIENT, false, false)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_TRANSACTION_UPDATED, false, false)); + } + + + /** + * adds implicit fields to the given type declaration + * + * @param td the recoder.java.TypeDeclaration to be enriched with + * implicit fields + */ + private void addImplicitRecoderFields(TypeDeclaration td) { + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_ERRONEOUS, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_INITIALIZED, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_PREPARED, true, true)); + + if (td instanceof ClassOrInterfaceDeclaration + //TODO weigl not understand this + //&& + //(td.getName() == null || ((TypeDeclaration) td).getStatementContainer() != null || + // td.getContainingReferenceType() != null) && + //(services.containingMethod(td) == null || !services.containingMethod(td).isStatic()) && + && td.isNestedType() + && !td.isStatic()) { + TypeDeclaration container = (TypeDeclaration) td.getParentNode().get(); + String id = container.getNameAsString(); + td.addField(new ClassOrInterfaceType(null, id), PipelineConstants.IMPLICIT_ENCLOSING_THIS, Modifier.Keyword.PRIVATE); + } + } + + protected void addClassInitializerStatusFields(TypeDeclaration td) { + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_ERRONEOUS, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_INITIALIZED, true, true)); + td.addMember(createImplicitRecoderField(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN), + PipelineConstants.IMPLICIT_CLASS_PREPARED, true, true)); + } + + private void addFieldsForFinalVars(TypeDeclaration td) { + final var vars = services.getFinalVariables(td); + if (!vars.isEmpty()) { + // not sure why, but doing it separated in two loops is much faster (for large programs) then just in one + // strangely, the effect is not measureable for e.g. the class init. fields... + for (final var v : vars) { + Type type = services.getType(v.getType()); + td.addMember(createImplicitRecoderField( + type, //TODO weigl check for arrays&co. + PipelineConstants.FINAL_VAR_PREFIX + v.getName(), false, true)); + } + } + } + + public void apply(TypeDeclaration td) { + addImplicitRecoderFields(td); + addFieldsForFinalVars(td); + if (!transformedObject && td.resolve().isJavaLangObject()) { + addGlobalImplicitRecoderFields(td); + transformedObject = true; + } + } + +} + diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/InstanceAllocationMethodBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/InstanceAllocationMethodBuilder.java new file mode 100644 index 00000000000..4bed1028d84 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/InstanceAllocationMethodBuilder.java @@ -0,0 +1,54 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; +import de.uka.ilkd.key.java.transformations.pipeline.PipelineConstants; +import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; + +/** + * creates a method declaration with no implementation. The methods intention is + * to allocate a new object of the type it is declared in and to return it. + * The functionality will be described using taclets + */ +public class InstanceAllocationMethodBuilder extends JavaTransformer { + + public InstanceAllocationMethodBuilder(TransformationPipelineServices services) { + super(services); + } + + private MethodDeclaration addAllocateMethod(TypeDeclaration type) { + NodeList modifiers = new NodeList<>(); + modifiers.add(new Modifier(Modifier.Keyword.PUBLIC)); + modifiers.add(new Modifier(Modifier.Keyword.STATIC)); + MethodDeclaration md = type.addMethod(PipelineConstants.IMPLICIT_INSTANCE_ALLOCATE, Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC); + md.setType(new ClassOrInterfaceType(null, type.getFullyQualifiedName().get())); + return md; + } + + + @Override + public void apply(TypeDeclaration td) { + //TODO only for classes? + if (td.isRecordDeclaration() && td.isClassOrInterfaceDeclaration()) { + addAllocateMethod(td); + } + } + +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JMLTransformer.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JMLTransformer.java new file mode 100644 index 00000000000..f6578b59984 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JMLTransformer.java @@ -0,0 +1,686 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.Position; +import com.github.javaparser.Range; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.BooleanLiteralExpr; +import com.github.javaparser.ast.key.KeyMergePointStatement; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.EmptyStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.visitor.VoidVisitorWithDefaults; +import de.uka.ilkd.key.settings.ProofIndependentSettings; +import de.uka.ilkd.key.speclang.PositionedString; +import de.uka.ilkd.key.speclang.jml.pretranslation.*; +import de.uka.ilkd.key.speclang.jml.pretranslation.TextualJMLAssertStatement.Kind; +import de.uka.ilkd.key.speclang.njml.JmlIO; +import de.uka.ilkd.key.speclang.translation.SLTranslationException; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.misc.Interval; +import org.key_project.util.collection.ImmutableList; +import org.key_project.util.collection.ImmutableSLList; +import org.key_project.util.java.StringUtil; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import static java.lang.String.format; + +/** + * RecodeR transformation that parses JML comments, and attaches code-like + * specifications (ghost fields, set statements, model methods) directly to the + * RecodeR AST. Note that internally, this class is highly similar to the class + * speclang.jml.SpecExtractor; if you change one of these classes, you probably + * need to change the other as well. + */ +public final class JMLTransformer extends JavaTransformer { + + public static final ImmutableList javaMods = ImmutableList.fromList( + Arrays.asList("abstract", "final", "private", "protected", "public", "static")); + /** + * JML markers left and right. + */ + private static final String JML = "/*@"; + private static final String JMR = "@*/"; + private static ImmutableList warnings = ImmutableSLList.nil(); + + /** + * Creates a transformation that adds JML specific elements, for example + * ghost fields and model method declarations. + * + * @param services the CrossReferenceServiceConfiguration to access model + * information + */ + public JMLTransformer(TransformationPipelineServices services) { + super(services); + warnings = ImmutableSLList.nil(); + } + + // ------------------------------------------------------------------------- + // private helper methods + // ------------------------------------------------------------------------- + + public static String getFullText(ParserRuleContext context) { + if (context.start == null || context.stop == null + || context.start.getStartIndex() < 0 || context.stop.getStopIndex() < 0) + return context.getText(); // Fallback + return context.start.getInputStream().getText(Interval.of(context.start.getStartIndex(), context.stop.getStopIndex())); + } + + public static ImmutableList getWarningsOfLastInstance() { + return warnings; + } + + /** + * Concatenates the passed comments in a position-preserving way. (see also + * JMLSpecExtractor::concatenate(), which does the same thing for KeY ASTs) + */ + private String concatenate(Comment[] comments) { + if (comments.length == 0) { + return ""; + } + StringBuilder sb = new StringBuilder(comments[0].getContent()); + + for (int i = 1; i < comments.length; i++) { + Position relativePos = comments[i].getRange().get().begin; + for (int j = 0; j < relativePos.line; j++) { + sb.append("\n"); + } + for (int j = 0; j < relativePos.column; j++) { + sb.append(" "); + } + sb.append(comments[i].getContent()); + } + return sb.toString(); + } + + /** + * Prepends the Java (i.e., non-JML) modifiers from the passed list to the + * passed PositionedString. Inserts whitespace in place of the JML modifiers + * (in order to preserve position information). + */ + private PositionedString convertToString(ImmutableList mods, ParserRuleContext ctx) { + StringBuilder sb = new StringBuilder(); + for (String mod : mods) { + if (javaMods.contains(mod)) { + sb.append(mod); + } else { + sb.append(StringUtil.repeat(" ", mod.length())); + } + sb.append(" "); + } + sb.append(getFullText(ctx)); + int column = ctx.start.getCharPositionInLine() - sb.toString().length(); + if (column < 0) { + column = 0; + } + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position(ctx.start.getLine(), column); + return new PositionedString(sb.toString(), + ctx.start.getTokenSource().getSourceName(), pos); + } + + /** + * Puts the JML modifiers from the passed list into a string enclosed in JML + * markers. + */ + private String getJMLModString(ImmutableList mods) { + StringBuilder sb = new StringBuilder(JML); + + for (String mod : mods) { + if (!javaMods.contains(mod)) { + sb.append(mod).append(" "); + } + } + + sb.append(JMR); + return sb.toString(); + } + + /** + * Recursively adds the passed position to the starting positions of the + * passed program element and its children. + */ + private void updatePositionInformation(Node pe, de.uka.ilkd.key.java.Position pos) { + if (pe.getRange().isPresent()) { + final var range = pe.getRange().get(); + Position oldStartPosition = range.begin; + int line = Math.max(0, pos.getLine() + oldStartPosition.line - 1); + int column = Math.max(0, pos.getColumn() + oldStartPosition.column - 1); + Position newPos = oldStartPosition.withColumn(column).withLine(line); + pe.setRange(range.withBegin(newPos)); + + // recurse to children + for (Node childNode : pe.getChildNodes()) { + updatePositionInformation(childNode, pos); + } + } + } + + /** + * Returns the children of the passed program element. + */ + private Node[] getChildren(Node pe) { + return pe.getChildNodes().toArray(new Node[0]); + } + + private Comment[] getCommentsAndSetParent(Node pe) { + assert pe != null; + if (pe.getAssociatedSpecificationComments().isEmpty()) { + return new Comment[0]; + } + NodeList var = pe.getAssociatedSpecificationComments().get(); + Comment[] result = var.toArray(new Comment[0]); + //TODO weigl, I think this is handled by JavaParser directly + for (Comment aResult : result) { + aResult.setParentNode(pe); + } + return result; + } + + private void transformFieldDecl(TextualJMLFieldDecl decl, Comment[] originalComments) + throws SLTranslationException { + assert originalComments.length > 0; + + // prepend Java modifiers + PositionedString declWithMods = convertToString(decl.getMods(), decl.getDecl()); + + // ghost or model? + boolean isGhost = false; + boolean isModel = false; + if (decl.getMods().contains("ghost")) { + isGhost = true; + } + if (decl.getMods().contains("model")) { + isModel = true; + if (isGhost) { + throw new SLTranslationException( + "JML field declaration cannot be both ghost and model!", + declWithMods.fileName, declWithMods.pos); + } + } + if (!(isGhost || isModel)) { + String s = declWithMods.text; + s = s.substring(0, s.indexOf(' ')); + throw new SLTranslationException( + format("Could not translate JML specification. You have either tried to use an" + + " unsupported keyword (%s) or a JML field declaration without a ghost or model modifier.", s), + declWithMods.fileName, declWithMods.pos); + } + + // determine parent, child index + Node astParent = originalComments[0].getParentNode().get().getParentNode().get(); + int childIndex = astParent.getChildNodes().indexOf(originalComments[0].getParentNode().get()); + + // parse declaration, attach to AST + FieldDeclaration fieldDecl; + try { + if (astParent instanceof TypeDeclaration) { + var result = services.getParser() + .parseBodyDeclaration(fillWithWhitespaces(declWithMods.pos, declWithMods.text)); + //TODO weigl add parseFieldDeclaration(declWithMods.text); ? + + if (result.isSuccessful()) { + fieldDecl = (FieldDeclaration) result.getResult().get(); + if (decl.getMods().contains("instance")) { + fieldDecl.getModifiers().removeIf(it -> it.getKeyword() == Modifier.Keyword.STATIC); + } + //updatePositionInformation(fieldDecl, declWithMods.pos); + // set comments: the original list of comments with the declaration, and the JML modifiers + NodeList newComments = new NodeList<>(Arrays.asList(originalComments)); + Comment jmlComment = new BlockComment(getJMLModString(decl.getMods())); + jmlComment.setParentNode(fieldDecl); + newComments.add(jmlComment); + fieldDecl.setAssociatedSpecificationComments(newComments); + ((TypeDeclaration) astParent).addMember(fieldDecl); + /* javadoc for attach() may say, this value is *not* used as a child index but as an index + into astParent.getMembers(), which only contains some of the children, not all. 0 is topmost + position, which should be a safe choice in any case. */ + + // add ghost or model modifier + NodeList mods = fieldDecl.getModifiers(); + if (mods == null) { + mods = new NodeList<>(); + } + mods.add(new Modifier(isGhost ? Modifier.Keyword.GHOST : Modifier.Keyword.MODEL)); + fieldDecl.setModifiers(mods); + + } else { + throw new SLTranslationException("Could not parse " + declWithMods.text, + declWithMods.fileName, declWithMods.pos); + } + } else { + assert astParent instanceof BlockStmt; + if (isModel) { + throw new SLTranslationException("JML model fields cannot be declared within a method!", + declWithMods.fileName, declWithMods.pos); + } + + var block = services.getParser().parseBlock( + fillWithWhitespaces(declWithMods.pos, "{" + declWithMods.text + "}")); + if (!block.isSuccessful()) { + throw new SLTranslationException("", declWithMods.fileName, declWithMods.pos); + } + List declStatement = block.getResult().get().getStatements(); + assert declStatement.size() == 1; + var vdecl = declStatement.get(0); + //updatePositionInformation(fieldDecl, declWithMods.pos); + ((BlockStmt) astParent).addStatement(childIndex, vdecl); + //attach((LocalVariableDeclaration) fieldDecl, (BlockStmt) astParent, childIndex); + // Unlike above, here the value is really a child index, and here the + // position really matters. + } + } catch (Throwable e) { + throw new SLTranslationException( + e.getMessage() + " (" + e.getClass().getName() + ")", + declWithMods.fileName, declWithMods.pos, e); + } + } + + private String fillWithWhitespaces(de.uka.ilkd.key.java.Position pos, String s) { + StringBuilder sb = new StringBuilder(); + sb.append("\n".repeat(Math.max(0, pos.getLine()))); + sb.append(" ".repeat(Math.max(0, pos.getColumn()))); + return sb.append(s).toString(); + } + + private void transformMethodDecl(TextualJMLMethodDecl decl, Comment[] originalComments) + throws SLTranslationException { + assert originalComments.length > 0; + + // prepend Java modifiers + PositionedString declWithMods = + new PositionedString(decl.getParsableDeclaration()); + + // only handle model methods + if (!decl.getMods().contains("model")) { + throw new SLTranslationException("JML method declaration has to be model!", + declWithMods.fileName, declWithMods.pos); + } + + // determine parent + TypeDeclaration astParent = (TypeDeclaration) originalComments[0].getParentNode().get(); + + // parse declaration, attach to AST + MethodDeclaration methodDecl; + var md = services.getParser() + .parseMethodDeclaration(declWithMods.text); + if (md.getResult().isPresent()) { + methodDecl = md.getResult().get(); + updatePositionInformation(methodDecl, declWithMods.pos); + astParent.addMember(methodDecl); + // about the 0 see the comment in transformFieldDecl() above + } else { + throw new SLTranslationException( + "could not parse", declWithMods.fileName, declWithMods.pos); + } + + // add model modifier + NodeList mods = methodDecl.getModifiers(); + mods.add(new Modifier(Modifier.Keyword.MODEL)); + if (decl.getMods().contains("two_state")) { + mods.add(new Modifier(Modifier.Keyword.TWO_STATE)); + } + if (decl.getMods().contains("no_state")) { + mods.add(new Modifier(Modifier.Keyword.NO_STATE)); + } + methodDecl.setModifiers(mods); + + // set comments: the original list of comments with the declaration, + // and the JML modifiers + NodeList newComments = new NodeList<>(originalComments); + Comment jmlComment = new LineComment(getJMLModString(decl.getMods())); + jmlComment.setParentNode(methodDecl); + newComments.add(jmlComment); + methodDecl.setAssociatedSpecificationComments(newComments); + + } + + private void transformAssertStatement(TextualJMLAssertStatement stat, + Comment[] originalComments) throws SLTranslationException { + if (originalComments.length <= 0) throw new IllegalArgumentException(); + + // determine parent, child index + BlockStmt astParent = (BlockStmt) originalComments[0] + .getParentNode().get().getParentNode().get(); + int childIndex = astParent.getChildNodes().indexOf(originalComments[0].getParentNode().get()); + + ParserRuleContext ctx = stat.getContext().first; + + // Convert to block with block contract, attach to AST. + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( + ctx.start.getLine(), + ctx.start.getCharPositionInLine()); + + try { + String comment = format( + "/*@ normal_behavior\n" + + " @ %s %s\n" + + " @ assignable \\strictly_nothing;\n" + + " @*/", stat.getKind() == Kind.ASSERT ? "ensures" : "ensures_free", stat.getClauseText()); + + BlockStmt block = services.getParser().parseBlock(format("{%n%s%n{;;}}", comment)).getResult().get(); + + updatePositionInformation(block, pos); + astParent.addStatement(childIndex, block); + } catch (Throwable e) { + throw new SLTranslationException( + format("%s (%s)", e.getMessage(), e.getClass().getName()), + ctx.start.getTokenSource().getSourceName(), pos, e); + } + } + + private void transformSetStatement(TextualJMLSetStatement stat, + Comment[] originalComments) throws SLTranslationException { + assert originalComments.length > 0; + + // determine parent, child index + BlockStmt astParent = (BlockStmt) originalComments[0].getParentNode().get().getParentNode().get(); + int childIndex = astParent.getChildNodes().indexOf(originalComments[0].getParentNode().get()); + + // parse statement, attach to AST + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( + stat.getAssignment().start.getLine(), + stat.getAssignment().start.getCharPositionInLine()); + try { + String assignment = getFullText(stat.getAssignment()).substring(3); + var result = services.getParser().parseBlock("{" + assignment + "}"); + var stmtList = result.getResult().get().getStatements(); + assert stmtList.size() == 1; + var assignStmt = stmtList.get(0); + shiftPosition(assignStmt, pos); + //updatePositionInformation(assignStmt, pos); + astParent.addStatement(childIndex, assignStmt); + } catch (Throwable e) { + throw new SLTranslationException( + e.getMessage() + " (" + e.getClass().getName() + ")", + stat.getAssignment().start.getTokenSource().getSourceName(), pos, e); + } + } + + private void shiftPosition(Node node, de.uka.ilkd.key.java.Position pos) { + shiftPosition(node, pos.getLine(), pos.getColumn()); + } + + private void shiftPosition(Node node, int line, int column) { + final var tokenRange = node.getTokenRange(); + if (tokenRange.isPresent()) { + var iter = tokenRange.get().iterator(); + iter.forEachRemaining(it -> { + if (it.getRange().isPresent()) { + var range = it.getRange().get(); + it.setRange( + Range.range(range.begin.line + line, + range.begin.column + column, + range.end.line + line, + range.end.column + column)); + } + }); + } + } + + private void transformMergePointDecl(TextualJMLMergePointDecl stat, + Comment[] originalComments) throws SLTranslationException { + assert originalComments.length > 0; + + // determine parent, child index + BlockStmt astParent = (BlockStmt) originalComments[0].getParentNode().get().getParentNode().get(); + int childIndex = astParent.getChildNodes().indexOf(originalComments[0].getParentNode().get()); + + // create MPS, attach to AST + try { + KeyMergePointStatement mps = new KeyMergePointStatement(new BooleanLiteralExpr(true)); + mps.setAssociatedSpecificationComments(new NodeList<>(Arrays.asList(originalComments))); + + Position startPosition = astParent.getChildNodes().get(childIndex).getRange().get().begin; + shiftPosition(mps, startPosition.line, startPosition.column); + astParent.addStatement(childIndex, mps); + } catch (Throwable e) { + throw new SLTranslationException( + format("%s (%s)", e.getMessage(), e.getClass().getName()), + stat.getSourceFileName(), stat.getApproxPosition(), e); + } + } + + private void transformClasslevelComments(TypeDeclaration td, String fileName) throws SLTranslationException { + // iterate over all pre-existing children + Node[] children = getChildren(td); + for (int i = 0; i <= children.length; i++) { + // collect comments + // (last position are comments of type declaration itself) + Comment[] comments = null; + if (i < children.length) { + comments = getCommentsAndSetParent(children[i]); + } else if (td.getAssociatedSpecificationComments().isPresent()) { + assert i > 0; // otherwise there wouldn't even be implicit + // fields + NodeList var = td.getAssociatedSpecificationComments().get(); + comments = var.toArray(new Comment[0]); + for (Comment c : comments) { + c.setParentNode(children[i - 1]); + } + } + if (comments == null || comments.length == 0) { + continue; + } + + // concatenate comments of child, determine position + String concatenatedComment = concatenate(comments); + Position recoderPos = comments[0].getRange().get().begin; + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( + recoderPos.line, recoderPos.column); + + // call preparser + JmlIO io = new JmlIO(); + ImmutableList constructs + = io.parseClassLevel(concatenatedComment, fileName, pos); + warnings = warnings.append(io.getWarnings()); + + // handle model and ghost declarations in textual constructs + // (and set assignments which RecodeR evilly left hanging *behind* + // the method to which they belong) + for (TextualJMLConstruct c : constructs) { + if (c instanceof TextualJMLFieldDecl) { + transformFieldDecl((TextualJMLFieldDecl) c, comments); + } else if (c instanceof TextualJMLMethodDecl) { + transformMethodDecl((TextualJMLMethodDecl) c, comments); + } else if (c instanceof TextualJMLSetStatement) { + if (i == 0 || !(children[i - 1] instanceof MethodDeclaration)) { + throw new SLTranslationException( + "A set assignment only allowed inside of a method body.", + fileName, pos); + } + Statement emptyStmt = new EmptyStmt(); + Comment emptyStmtComment = new BlockComment(); + emptyStmtComment.setParentNode(emptyStmt); + BlockStmt methodBody = ((MethodDeclaration) children[i - 1]).getBody().get(); + methodBody.addStatement(emptyStmt); + transformSetStatement((TextualJMLSetStatement) c, new Comment[]{emptyStmtComment}); + } + } + } + } + + private void transformMethodlevelCommentsHelper(Node pe, String fileName) throws SLTranslationException { + // recurse to all pre-existing children + Node[] children = getChildren(pe); + for (Node aChildren : children) { + transformMethodlevelCommentsHelper(aChildren, fileName); + } + + if (pe instanceof MethodDeclaration) + return; + + // get comments + Comment[] comments = getCommentsAndSetParent(pe); + if (comments.length == 0) { + return; + } + + // concatenate comments, determine position + String concatenatedComment = concatenate(comments); + Position recoderPos = comments[0].getRange().get().begin; + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( + recoderPos.line, recoderPos.column); + + // call preparser + JmlIO io = new JmlIO(); + ImmutableList constructs + = io.parseMethodLevel(concatenatedComment, fileName, pos); + warnings = warnings.append(io.getWarnings()); + + // handle ghost declarations and set assignments in textual constructs + for (TextualJMLConstruct c : constructs) { + if (c instanceof TextualJMLFieldDecl) { + transformFieldDecl((TextualJMLFieldDecl) c, comments); + } else if (c instanceof TextualJMLSetStatement) { + transformSetStatement((TextualJMLSetStatement) c, comments); + } else if (c instanceof TextualJMLMergePointDecl) { + transformMergePointDecl((TextualJMLMergePointDecl) c, comments); + } else if (c instanceof TextualJMLAssertStatement) { + transformAssertStatement((TextualJMLAssertStatement) c, comments); + } + } + } + + public void apply(TypeDeclaration td) { + //assert false; + } + + public void analyze() { + for (var unit : cache.getUnits()) { + // move comments of type declarations to previous type declaration + // (because RecodeR attaches comments appearing at the end of a type + // declaration to the next one; for example, in a unit with the + // text + // class A { + // //@ invariant true; + // } + // class B {} + // the invariant will appear as a comment of B. We move it to A + // here.) + for (int j = 1; j < unit.getTypes().size(); j++) { + TypeDeclaration td1 = unit.getType(j - 1); + TypeDeclaration td2 = unit.getType(j); + td1.setAssociatedSpecificationComments(td2.getAssociatedSpecificationComments().get()); + } + + // copy comments of compilation unit to last type declaration + // (because RecodeR attaches comments appearing at the end of the + // last type declaration to the unit; for example, in a unit with + // the text + // class A {} + // class B { + // //@ invariant true; + // } + // the invariant will appear as a comment of the unit. We move it to B here.) + if (unit.getTypes().size() > 0) { + TypeDeclaration td = unit.getType(unit.getTypes().size() - 1); + NodeList tdComments = new NodeList<>(); + if (unit.getComments() != null) { + tdComments.addAll(TransformationPipelineServices.cloneList( + unit.getAssociatedSpecificationComments().get())); + } + td.setAssociatedSpecificationComments(tdComments); + } + + // iterate over all type declarations of the compilation unit + var typeDeclarations = getAllTypes(unit); + for (TypeDeclaration td : typeDeclarations) { + // collect pre-existing operations + List constructorList = td.getConstructors(); + List methodList = td.getMethods(); + } + } + } + + private List> getAllTypes(CompilationUnit unit) { + var seq = new LinkedList>(); + class TypesCollector extends VoidVisitorWithDefaults { + @Override + public void defaultAction(Node n, Void arg) { + if (n instanceof TypeDeclaration) { + seq.add((TypeDeclaration) n); + } + } + } + unit.accept(new TypesCollector(), null); + return seq; + } + + public void apply() { + // abort if JML is disabled + // if(!ProofSettings.DEFAULT_SETTINGS.getGeneralSettings().useJML()) { + if (!ProofIndependentSettings.DEFAULT_INSTANCE.getGeneralSettings().useJML()) { + return; + } + + try { + // iterate over all compilation units + for (CompilationUnit unit : cache.getUnits()) { + // iterate over all type declarations of the compilation unit + for (TypeDeclaration td : getAllTypes(unit)) { + // collect pre-existing operations + List constructorList = td.getConstructors(); + List methodList = td.getMethods(); + + // fix mu: units carry an artificial file name. use getOriginalDataLocation instead + //DataLocation dl = unit.getOriginalDataLocation(); + /* If the DataLocation is not set, we set an invalid URL string. + * This may cause a MalformedURLException later if a parsing error occurs, + * but at least show the error message of the parser. */ + String resource = unit.getStorage().map(it -> it.getPath().toFile().toString()) + .orElse("UNKNOWN:unknown"); + + transformClasslevelComments(td, resource); + + // iterate over all pre-existing constructors + for (var aConstructorList : constructorList) { + transformMethodlevelCommentsHelper(aConstructorList.getBody(), resource); + } + + // iterate over all pre-existing methods + for (var aMethodList : methodList) { + // might be ImplicitEnumMethod + if (aMethodList.getBody().isPresent()) { + transformMethodlevelCommentsHelper(aMethodList.getBody().get(), resource); + } + } + } + } + } catch (SLTranslationException e) { + // Wrap the exception into a runtime exception because recoder does + // not allow otherwise. It will be unwrapped later ... + throw new RuntimeException(e); + // RuntimeException runtimeE = new RuntimeException(e.getMessage() + // + "\n" + e.getFileName() + // + ", line " + e.line + // + ", column " + e.column); + // runtimeE.setStackTrace(e.getStackTrace()); + // throw runtimeE; + } + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JavaTransformer.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JavaTransformer.java new file mode 100644 index 00000000000..46e7aa823c6 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/JavaTransformer.java @@ -0,0 +1,127 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.AssignExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.stmt.ExpressionStmt; + +/** + * The Java DL requires some implicit fields, that are available in each + * Java class. The name of the implicit fields is usually enclosed + * between two angle brackets. + * To access the fields in a uniform way, they are added as usual + * fields to the classes, in particular this allows us to parse them in + * more easier. + * For further information see also + *

    + *
  • {@link ImplicitFieldAdder}
  • + *
  • {@link CreateObjectBuilder}
  • + *
  • {@link PrepareObjectBuilder}
  • + *
+ *

+ * Performance of these classes was low, so information that is shared between + * all instances of a transformation set has been outsourced to a transformation + * cache. + */ +public abstract class JavaTransformer { + /** + * + */ + protected final TransformationPipelineServices services; + + /** + * a cache object that stores information which is needed by + * and common to many transformations. it includes the + * compilation units, the declared classes, and information + * for local classes. + */ + protected final TransformationPipelineServices.TransformerCache cache; + + /** + * creates a transformer for the recoder model + * + * @param services the CrossReferenceServiceConfiguration to access + * model information + */ + public JavaTransformer(TransformationPipelineServices services) { + this.services = services; + this.cache = services.getCache(); + } + + /** + * The method is called for each type declaration of the compilation + * unit and initiates the syntactical transformation. If you want to + * descend in inner classes you have to implement the recursion by + * yourself. + */ + public abstract void apply(TypeDeclaration td); + + + /* + protected class FinalOuterVarsCollector extends SourceVisitorExtended { + + private final HashMap> lc2fv; + + public FinalOuterVarsCollector() { + super(); + lc2fv = cache.getLocalClass2FinalVarMapping(); + } + + public void walk(SourceElement s) { + s.accept(this); + if (s instanceof Node) { + final Node pe = (Node) s; + for (int i = 0, sz = pe.getChildCount(); i < sz; i++) { + walk(pe.getChildAt(i)); + } + } + } + + public void visitVariableReference(VariableReference vr) { + final DefaultCrossReferenceSourceInfo si = (DefaultCrossReferenceSourceInfo) services.getSourceInfo(); + final Variable v = si.getVariable(vr.getName(), vr); + + final ReferenceType containingReferenceTypeOfProgVarV = si.getContainingReferenceType((Node) v); + ReferenceType ct = si.getContainingReferenceType(vr); + if (containingReferenceTypeOfProgVarV != ct && + v instanceof VariableSpecification && !(v instanceof FieldSpecification)) { + + while (ct instanceof TypeDeclaration && ct != containingReferenceTypeOfProgVarV) { + List vars = lc2fv.get(ct); + if (vars == null) { + vars = new LinkedList(); + } + if (!vars.contains(v)) { + vars.add(v); + } + lc2fv.put(ct, vars); + ct = si.getContainingReferenceType(ct); + } + } + } + } + */ + + + public static ExpressionStmt assign(Expression lhs, Expression rhs) { + return new ExpressionStmt(new AssignExpr(lhs, rhs, AssignExpr.Operator.ASSIGN)); + } + + public static Expression attribute(Expression context, String field) { + return new FieldAccessExpr(context, field); + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/LocalClassTransformation.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/LocalClassTransformation.java new file mode 100644 index 00000000000..fc5dda40f3c --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/LocalClassTransformation.java @@ -0,0 +1,52 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.ThisExpr; + +/** + * Local and anonymous classes may access variables from the creating context + * if they are declared final and initialised. + *

+ * This transformation searches for such final variables and replaces them by + * an implicit variable. + *

+ * Additionally a pseudo name is assigned to anonymous classes to allow to + * access them despite all. + * + * @author engelc + */ +public class LocalClassTransformation extends JavaTransformer { + + public LocalClassTransformation(TransformationPipelineServices services) { + super(services); + } + + @Override + public void apply(TypeDeclaration td) { + var outerVars = services.getFinalVariables(td); + if (outerVars != null) { + for (var v : outerVars) { + for (final var vr : services.getUsages(v, td)) { + FieldAccessExpr fr = new FieldAccessExpr(new ThisExpr(), + PipelineConstants.FINAL_VAR_PREFIX + v.getName()); + //TODO td.replace(vr, fr); + } + } + } + } + +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java new file mode 100644 index 00000000000..dc9e749c6e4 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java @@ -0,0 +1,25 @@ +package de.uka.ilkd.key.java.transformations.pipeline; + +/** + * @author Alexander Weigl + * @version 1 (11/6/21) + */ +public interface PipelineConstants { + String CONSTRUCTOR_NORMALFORM_IDENTIFIER = "$init"; + String OBJECT_INITIALIZER_IDENTIFIER = "$objectInitializer"; + String IMPLICIT_CLASS_PREPARED = "$classPrepared"; + String IMPLICIT_CLASS_INITIALIZED = "$classInitialized"; + String IMPLICIT_CLASS_INIT_IN_PROGRESS = "$classInitializationInProgress"; + String IMPLICIT_CLASS_ERRONEOUS = "$classErroneous"; + String IMPLICIT_CREATED = "$created"; + String IMPLICIT_INITIALIZED = "$initialized"; + String IMPLICIT_TRANSIENT = "$transient"; + String IMPLICIT_TRANSACTION_UPDATED = "$transactionConditionallyUpdated"; + String IMPLICIT_ENCLOSING_THIS = "$enclosingThis"; + String FINAL_VAR_PREFIX = "_outer_final_"; + String VIRTUAL_METHOD_FOR_PARSING = "$virtual_method_for_parsing"; + String VIRTUAL_CLASS_FOR_PARSING = "$virtual_class_for_parsing"; + String IMPLICIT_OBJECT_PREPARE = "$prepare"; + String IMPLICIT_OBJECT_PREPARE_ENTER = "$prepareEnter"; + String IMPLICIT_INSTANCE_ALLOCATE = ""; +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PrepareObjectBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PrepareObjectBuilder.java new file mode 100644 index 00000000000..a4562ef6f45 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PrepareObjectBuilder.java @@ -0,0 +1,152 @@ +// This file is part of KeY - Integrated Deductive Software Design +// +// Copyright (C) 2001-2011 Universitaet Karlsruhe (TH), Germany +// Universitaet Koblenz-Landau, Germany +// Chalmers University of Technology, Sweden +// Copyright (C) 2011-2014 Karlsruhe Institute of Technology, Germany +// Technical University Darmstadt, Germany +// Chalmers University of Technology, Sweden +// +// The KeY system is protected by the GNU General +// Public License. See LICENSE.TXT for details. +// + +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.expr.SuperExpr; +import com.github.javaparser.ast.expr.ThisExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.VoidType; +import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; +import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; + +import java.util.ArrayList; +import java.util.List; + +import static de.uka.ilkd.key.java.transformations.pipeline.PipelineConstants.IMPLICIT_OBJECT_PREPARE; +import static de.uka.ilkd.key.java.transformations.pipeline.PipelineConstants.IMPLICIT_OBJECT_PREPARE_ENTER; + +/** + * Creates the preparation method for pre-initilizing the object fields + * with their default settings. + */ +public class PrepareObjectBuilder extends JavaTransformer { + public PrepareObjectBuilder(TransformationPipelineServices services) { + super(services); + } + + /** + * returns all fields of the class cd in source code order. The + * method is a work around for a bug in recoder 0.70 as there source + * code order is not respected. May become obsolete if newer recoder + * versions are used. + */ + private List getFields(TypeDeclaration cd) { + List result = new ArrayList<>(); + outer: + for (FieldDeclaration fd : cd.getFields()) { + for (Modifier mod : fd.getModifiers()) { + if (mod.getKeyword() == Modifier.Keyword.MODEL) + continue outer; + } + var fields = fd.getVariables(); + result.addAll(fields); + } + return result; + } + + /** + * creates the assignments of the field variables to their default values + * and inserts them to the given body list + * + * @return the same list body that has been handed over as parameter + */ + private NodeList defaultSettings(List fields) { + if (fields == null) { + return new NodeList<>(); + } + NodeList result = new NodeList(); + for (FieldDeclaration field : fields) { + if (!field.isStatic()) { + for (VariableDeclarator variable : field.getVariables()) { + SimpleName fieldId = variable.getName(); + if (!fieldId.getIdentifier().startsWith("<")) { + result.add(assign((attribute(new ThisExpr(), fieldId.getIdentifier())), + services.getDefaultValue(field.resolve().getType()))); + + } + } + } + } + return result; + } + + /** + * creates an implicit method called 'prepare', that sets all + * attributes to their default values + */ + protected BlockStmt createPrepareBody(TypeDeclaration type) { + var body = new NodeList(); + if (type.resolve().isJavaLangObject()) { + // we can access the implementation + body.add(new ExpressionStmt(new MethodCallExpr(new SuperExpr(), IMPLICIT_OBJECT_PREPARE))); + body.addAll(defaultSettings(type.getFields())); + } + return new BlockStmt(body); + } + + /** + * creates the implicit <prepare> method that + * sets the fields of the given type to its default values + * + * @param type the TypeDeclaration for which the + * <prepare> is created + * @return the implicit <prepare> method + */ + public MethodDeclaration createMethod(TypeDeclaration type) { + NodeList modifiers = new NodeList(new Modifier(Modifier.Keyword.PROTECTED)); + MethodDeclaration md = new MethodDeclaration(modifiers, + new VoidType(), + IMPLICIT_OBJECT_PREPARE); + md.setBody(createPrepareBody(type)); + return md; + } + + /** + * creates the implicit <prepareEnter> method that + * sets the fields of the given type to its default values + * + * @param type the TypeDeclaration for which the + * <prepare> is created + * @return the implicit <prepare> method + */ + public MethodDeclaration createMethodPrepareEnter(TypeDeclaration type) { + NodeList modifiers = new NodeList<>(new Modifier(Modifier.Keyword.PRIVATE)); + MethodDeclaration md = new MethodDeclaration(modifiers, + new VoidType(), + IMPLICIT_OBJECT_PREPARE_ENTER); + md.setBody(createPrepareBody(type)); + return md; + } + + + /** + * entry method for the constructor normalform builder + * + * @param td the TypeDeclaration + */ + public void apply(TypeDeclaration td) { + if (td instanceof ClassOrInterfaceDeclaration) { + td.addMember(createMethod(td)); + td.addMember(createMethodPrepareEnter(td)); + } + } + +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformationPipelineServices.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformationPipelineServices.java new file mode 100644 index 00000000000..7e9e1a5ad77 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformationPipelineServices.java @@ -0,0 +1,442 @@ +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration; +import com.github.javaparser.resolution.types.ResolvedReferenceType; +import com.github.javaparser.resolution.types.ResolvedType; +import com.github.javaparser.symbolsolver.model.resolution.SymbolReference; +import de.uka.ilkd.key.java.JavaService; +import de.uka.ilkd.key.java.transformations.ConstantExpressionEvaluator; +import de.uka.ilkd.key.java.transformations.EvaluationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Alexander Weigl + * @version 1 (11/2/21) + */ +public class TransformationPipelineServices { + private static final Logger LOGGER = LoggerFactory.getLogger(TransformationPipelineServices.class); + + @Nonnull + private final TransformerCache cache; + + @Nonnull + private final JavaService javaService; + + + public TransformationPipelineServices(@Nonnull JavaService javaService, @Nonnull TransformerCache cache) { + this.cache = cache; + this.javaService = javaService; + } + + @Nonnull + public TransformerCache getCache() { + return cache; + } + + public ConstantExpressionEvaluator getConstantEvaluator() { + return new ConstantExpressionEvaluator(javaService.createJavaParser()); + } + + + /*protected TypeDeclaration containingClass(TypeDeclaration td) { + Node container = td.getContainingReferenceType(); + if (container == null) { + container = td.getParentNode().get(); + } + while (!(container instanceof TypeDeclaration)) { + container = container.getParentNode().get(); + } + return (TypeDeclaration) container; + }*/ + + + public String getId(TypeDeclaration td) { + return td.getNameAsString(); + } + + protected MethodDeclaration containingMethod(TypeDeclaration td) { + Node container = td.getParentNode().get(); + while (container != null && !(container instanceof MethodDeclaration)) { + container = container.getParentNode().get(); + } + return (MethodDeclaration) container; + } + + /** + * returns the default value of the given type + * according to JLS Sect. 4.5.5 + * + * @return the default value of the given type + * according to JLS Sect. 4.5.5 + */ + public Expression getDefaultValue(Type type) { + if (type instanceof ReferenceType) { + return new NullLiteralExpr(); + } else if (type instanceof PrimitiveType) { + PrimitiveType ptype = (PrimitiveType) type; + switch (ptype.getType()) { + case BOOLEAN: + return new BooleanLiteralExpr(false); + case KEY_BIGINT: + case BYTE: + case SHORT: + case INT: + return new IntegerLiteralExpr("0"); + case LONG: + return new LongLiteralExpr("0"); + + case CHAR: + return new CharLiteralExpr((char) 0); + case FLOAT: + case DOUBLE: + case KEY_REAL: + return new DoubleLiteralExpr("0.0"); + + case KEY_LOCSET: + case KEY_SEQ: + case KEY_FREE: + case KEY_MAP: + throw new IllegalArgumentException("TODO"); + //return new KeyEscapeExpression(null, new NodeList<>()); + } + } + LOGGER.error("makeImplicitMembersExplicit: unknown primitive type: {}", type); + return null; + } + + public Type getType(Expression n) { + return null; + } + + public ClassOrInterfaceType getType(String... names) { + ClassOrInterfaceType type = null; + for (String name : names) { + type = new ClassOrInterfaceType(type, name); + } + return type; + } + + public Name getName(String... names) { + Name type = null; + for (String name : names) { + type = new Name(type, name); + } + return type; + } + + /** + * returns true if the given FieldDeclaration denotes a constant + * field. A constant field is declared as final and static and + * initialised with a time constant, which is not prepared or + * initialised here. ATTENTION: this is a derivation from the JLS + * but the obtained behaviour is equivalent as we only consider + * completely compiled programs and not partial compilations. The + * reason for preparation and initialisation of comnpile time + * constant fields is due to binary compatibility reasons. + */ + private boolean isConstant(Expression expr) { + ConstantExpressionEvaluator ce = getConstantEvaluator(); + try { + return ce.isCompileTimeConstant(expr); + } catch (EvaluationException e) { + e.printStackTrace(); + return false; + } + } + + public boolean isConstant(Optional initializer) { + return initializer.map(this::isConstant).orElse(false); + } + + public ClassOrInterfaceType getType(TypeDeclaration decl) { + return new ClassOrInterfaceType(null, decl.getName(), null); + } + + public ResolvedTypeDeclaration getJavaLangObject() { + return javaService.getTypeSolver().getSolvedJavaLangObject(); + } + + public Type getType(ResolvedType type) { + if (type.isArray()) { + //TODO weigl type.arrayLevel() + return new ArrayType(getType(type.asArrayType().getComponentType())); + } + + if (type.isReferenceType()) { + return getType(type.asReferenceType().getQualifiedName().split("[.]")); + } + + if (type.isPrimitive()) { + return new PrimitiveType(PrimitiveType.Primitive.valueOf(type.asPrimitive().name())); + } + + return null; + } + + public List> getUsages(ResolvedFieldDeclaration v, Node node) { + //TODO + return Collections.emptyList();//;resolver.solveSymbol(v.getName(), node); + } + + /** + * The list of statements is the smallest list that contains a copy + * assignment for each instance field initializer of class cd, + * e.g. i = 0; for public int i = 0; or + * a reference to the private method + * <objectInitializer>i refering to the i-th object + * initializer of cd. These private declared methods are created on + * the fly. Example for + *

+     * class C {
+     * int i = 0;
+     * {
+     * int j = 3;
+     * i = j + 5;
+     * }
+     * 

+ * public C () {} ... + * }

+ * the following list of size two is returned + *
+     * [ i = 0;,  <objectInitializer>0(); ]
+     * 
+ * where
+     * private <objectInitializer>0() {
+     * int j = 3;
+     * i = j + 5;
+     * }
+ *
+ * + * @param cd the TypeDeclaration of which the initilizers have to + * be collected + * @return the list of copy assignments and method references + * realising the initializers. + */ + public NodeList getInitializers(ClassOrInterfaceDeclaration cd) { + NodeList result = new NodeList<>(); + NodeList mdl = new NodeList<>(); + + var initializers = + cd.getMembers().stream() + .filter(BodyDeclaration::isInitializerDeclaration) + .map(it -> (InitializerDeclaration) it) + .filter(it -> !it.isStatic()) + .collect(Collectors.toList()); + + + for (InitializerDeclaration initializer : initializers) { + + String name = PipelineConstants.OBJECT_INITIALIZER_IDENTIFIER + mdl.size(); + var initializerMethod = cd.addMethod(name, Modifier.Keyword.PRIVATE); + initializerMethod.setBody(initializer.getBody().clone()); + mdl.add(initializerMethod); + result.add(new ExpressionStmt(new MethodCallExpr(null, new NameExpr(name)))); + } + + var memberFields = + cd.getMembers().stream() + .filter(BodyDeclaration::isFieldDeclaration) + .map(it -> (FieldDeclaration) it) + .filter(it -> !it.isStatic()) + .collect(Collectors.toList()); + + for (FieldDeclaration field : memberFields) { + for (VariableDeclarator variable : field.getVariables()) { + if (variable.getInitializer().isPresent()) { + Expression fieldInit = variable.getInitializer().get(); + final var access = new FieldAccessExpr( + new ThisExpr(), new NodeList<>(), variable.getName()); + var fieldCopy = new AssignExpr(access, fieldInit.clone(), AssignExpr.Operator.ASSIGN); + result.add(new ExpressionStmt(fieldCopy)); + } + } + } + return result; + } + + public static NodeList cloneList(NodeList list) { + if (list == null) { + return null; + } + var seq = list.stream() + .map(Node::clone) + .map(it -> (N) it) + .collect(Collectors.toList()); + return new NodeList<>(seq); + } + + public Expression getDefaultValue(ResolvedType type) { + if (type.isPrimitive()) { + var p = type.asPrimitive(); + if (p.isBoolean()) { + return new BooleanLiteralExpr(false); + } + + switch (p.name()) { + case "int": + case "byte": + case "short": + return new IntegerLiteralExpr("0"); + case "char": + return new CharLiteralExpr("0"); + case "float": + case "double": + return new DoubleLiteralExpr("0.0"); + } + } + + if (type.isReferenceType() + || type.isNull() + || type.isArray()) { + return new NullLiteralExpr(); + } + + if (type.isVoid()) { + throw new RuntimeException(); + } + + return null; + } + + public JavaParser getParser() { + return javaService.createJavaParser(); + } + + /** + * Cache of important data. This is done mainly for performance reasons. + * It contains the following info: + * - list of comp. units + * - their class declarations + * - a mapping from local classes to their needed final variables. + *

+ * Objects are created upon the first request. + * + * @author MU + */ + public static class TransformerCache { + private final NodeList cUnits = new NodeList<>(); + private Set> classDeclarations; + //private HashMap> localClass2FinalVar; + //private HashMap> typeDeclaration2allSupertypes; + + public TransformerCache(List cUnits) { + this.cUnits.addAll(cUnits); + } + + public Set> typeDeclarations() { + if (classDeclarations == null) { + init(); + } + return classDeclarations; + } + + private void init() { + class FindTypes extends VoidVisitorAdapter { + @Override + public void visit(EnumDeclaration n, Void arg) { + classDeclarations.add(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassOrInterfaceDeclaration n, Void arg) { + classDeclarations.add(n); + super.visit(n, arg); + } + + @Override + public void visit(RecordDeclaration n, Void arg) { + classDeclarations.add(n); + super.visit(n, arg); + } + + @Override + public void visit(AnnotationDeclaration n, Void arg) { + classDeclarations.add(n); + super.visit(n, arg); + } + } + cUnits.accept(new FindTypes(), null); + } + + public Set classDeclarations() { + return typeDeclarations().stream() + .filter(it -> it.isClassOrInterfaceDeclaration()) + .map(it -> (ClassOrInterfaceDeclaration) it) + .collect(Collectors.toSet()); + } + + public Set enumDeclarations() { + return typeDeclarations().stream() + .filter(it -> it.isEnumDeclaration()) + .map(it -> (EnumDeclaration) it) + .collect(Collectors.toSet()); + } + + + public Set recordDeclarations() { + return typeDeclarations().stream() + .filter(it -> it.isRecordDeclaration()) + .map(it -> (RecordDeclaration) it) + .collect(Collectors.toSet()); + } + + public List getAllSupertypes(TypeDeclaration td) { + return td.resolve().getAncestors(); + /* + if (td.isEnumDeclaration()) { + return Collections.singletonList(getType("java", "lang", "Enum")); + } + + if (td.isRecordDeclaration()) { + return Collections.singletonList(getType("java", "lang", "Record")); + } + + if (td.isAnnotationDeclaration()) { + return Collections.emptyList(); + } + + ClassOrInterfaceDeclaration cd = (ClassOrInterfaceDeclaration) td; + var a = cd.resolve(); + return typeDeclaration2allSupertypes.get(td);*/ + } + + public List getUnits() { + return cUnits; + } + + } + + public Collection getFinalVariables(TypeDeclaration n) { + var seq = new LinkedList(); + while (n.isNestedType()) { + n = (TypeDeclaration) n.getParentNode().get(); + var fields = n.resolve().getAllNonStaticFields(); + seq.addAll(fields); + } + return seq; + } + + public LinkedList getFinalVariables(LambdaExpr n) { + var seq = new LinkedList(); + return seq; + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformerCache.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformerCache.java new file mode 100644 index 00000000000..7190275811a --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/TransformerCache.java @@ -0,0 +1,9 @@ +package de.uka.ilkd.key.java.transformations.pipeline; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.type.ReferenceType; + +import java.util.*; diff --git a/key/key.java/src/test/java/KeyJavaPipelineTest.java b/key/key.java/src/test/java/KeyJavaPipelineTest.java new file mode 100644 index 00000000000..842d002e33f --- /dev/null +++ b/key/key.java/src/test/java/KeyJavaPipelineTest.java @@ -0,0 +1,84 @@ +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.TypeDeclaration; +import de.uka.ilkd.key.java.JavaService; +import de.uka.ilkd.key.java.transformations.KeyJavaPipeline; +import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; +import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * @author Alexander Weigl + * @version 1 (19.02.22) + */ +public class KeyJavaPipelineTest { + public KeyJavaPipeline createPipelineTest(File testFolder) throws FileNotFoundException { + var js = new JavaService(Collections.singleton(testFolder)); + var inputFolder = new File(testFolder, "input"); + final var jp = js.createJavaParser(); + var files = inputFolder.listFiles(); + var cu = new ArrayList(); + for (File it : files) { + var r = jp.parse(it); + var c = r.getResult().get(); + cu.add(c); + } + var services = new TransformationPipelineServices(js, new TransformationPipelineServices.TransformerCache(cu)); + var kjp = KeyJavaPipeline.createDefault(services); + var kjp2 = new KeyJavaPipeline(services); + var cnt = 0; + for (JavaTransformer step : kjp.getSteps()) { + kjp2.add(step); + final var file = new File(new File(testFolder, "actual"), + String.format("%02d_%s", ++cnt, step.getClass().getSimpleName())); + kjp2.add(new DebugOutputTransformer(file, services)); + } + return kjp2; + } + + @Test + void simple() throws FileNotFoundException { + var pt = createPipelineTest(new File("pipelineTests/simple")); + pt.apply(); + } + + private static class DebugOutputTransformer extends JavaTransformer { + final File outputFolder; + final Set alreadyWritten = new HashSet<>(); + private static final Logger LOGGER = LoggerFactory.getLogger(DebugOutputTransformer.class); + + + public DebugOutputTransformer(File s, TransformationPipelineServices services) { + super(services); + outputFolder = s; + } + + @Override + public void apply(TypeDeclaration td) { + outputFolder.mkdirs(); + for (CompilationUnit unit : services.getCache().getUnits()) { + var name = unit.getPrimaryTypeName().get(); + var file = new File(outputFolder, name + ".java"); + if (!alreadyWritten.contains(file)) { + alreadyWritten.add(file); + try { + Files.writeString(file.toPath(), unit.toString()); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } + } + } + } + } +} diff --git a/key/settings.gradle b/key/settings.gradle index a203b6db011..cbc1556a1d3 100644 --- a/key/settings.gradle +++ b/key/settings.gradle @@ -12,3 +12,5 @@ include "key.core.symbolic_execution.example" include 'recoder' include 'keyext.ui.testgen' include 'keyext.exploration' +include 'key.java' + From 245ffdd66c9eae8f39ba2b27a650e7922dab3abb Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 19 Feb 2022 13:55:39 +0100 Subject: [PATCH 002/225] fixing the first errors --- .../pipelineTests/simple/input/Test.java | 2 +- .../ClassInitializeMethodBuilder.java | 12 ++++---- .../ClassPreparationMethodBuilder.java | 7 +++-- .../pipeline/CreateBuilder.java | 2 +- .../pipeline/CreateObjectBuilder.java | 2 +- .../pipeline/PipelineConstants.java | 2 +- .../src/test/java/KeyJavaPipelineTest.java | 29 ++++++++++++++++++- 7 files changed, 43 insertions(+), 13 deletions(-) diff --git a/key/key.java/pipelineTests/simple/input/Test.java b/key/key.java/pipelineTests/simple/input/Test.java index afdb0812a2e..68e89bfae91 100644 --- a/key/key.java/pipelineTests/simple/input/Test.java +++ b/key/key.java/pipelineTests/simple/input/Test.java @@ -1,7 +1,7 @@ public class Test { public static int abc; static { - abc = 2; + abc = 1+1; // should be resolved to 2 } public int memberVar; diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java index 5da1c3ef4ad..29ed0ca8ab0 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassInitializeMethodBuilder.java @@ -37,7 +37,7 @@ * preparation. */ public class ClassInitializeMethodBuilder extends JavaTransformer { - public static final String CLASS_INITIALIZE_IDENTIFIER = ""; + public static final String CLASS_INITIALIZE_IDENTIFIER = "$clinit"; /** * Creates an instance of the class preparation method model @@ -148,7 +148,7 @@ private NodeList getInitializers(TypeDeclaration typeDeclaration) * */ private CatchClause createCatchClause(String caughtType, String caughtParam, ThrowStmt t) { - NodeList catcher = new NodeList(); + NodeList catcher = new NodeList<>(); var resetInitInProgress = assign(new KeyPassiveExpression( new NameExpr(new SimpleName(PipelineConstants.IMPLICIT_CLASS_INIT_IN_PROGRESS))), @@ -186,8 +186,9 @@ private TryStmt createInitializerExecutionTryBlock(TypeDeclaration td) { if (td instanceof ClassOrInterfaceDeclaration && !td.resolve().isJavaLangObject()) { var cd = (ClassOrInterfaceDeclaration) td; - final var superType = cd.getExtendedTypes(0); - final var scope = new NameExpr(superType.getName()); //TODO convert fqn + var type = cd.resolve(); + final var superType = type.getAncestors().get(0); + final var scope = new NameExpr(superType.getQualifiedName()); initializerExecutionBody.add(0, new ExpressionStmt( new KeyPassiveExpression( @@ -218,7 +219,6 @@ private TryStmt createInitializerExecutionTryBlock(TypeDeclaration td) { * creates the body of the initialize method */ private BlockStmt createInitializeMethodBody(TypeDeclaration td) { - var methodBody = new NodeList(); var clInitializeBody = new NodeList(); var clInitNotInProgressBody = new NodeList(); @@ -320,7 +320,7 @@ private BlockStmt createInitializeMethodBody(TypeDeclaration td) { * @return the created class preparation method */ private MethodDeclaration createInitializeMethod(TypeDeclaration td) { - NodeList modifiers = new NodeList(); + NodeList modifiers = new NodeList<>(); modifiers.add(new Modifier(Modifier.Keyword.STATIC)); modifiers.add(new Modifier(Modifier.Keyword.PUBLIC)); MethodDeclaration md = new MethodDeclaration(modifiers, diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java index fa7e0750ffe..258475f74ca 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/ClassPreparationMethodBuilder.java @@ -42,7 +42,7 @@ public class ClassPreparationMethodBuilder extends JavaTransformer { private static final Logger LOGGER = LoggerFactory.getLogger(ClassPreparationMethodBuilder.class); - public static final String CLASS_PREPARE_IDENTIFIER = ""; + public static final String CLASS_PREPARE_IDENTIFIER = "$clprepare"; /** * maps a class to its static NON-CONSTANT fields @@ -134,7 +134,10 @@ private MethodDeclaration createPrepareMethod(TypeDeclaration td) { MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), // return type is void CLASS_PREPARE_IDENTIFIER); - method.setBody(new BlockStmt(class2staticFields.get(td))); + final var statements = class2staticFields.get(td); + if (statements != null) { + method.setBody(new BlockStmt(statements)); + } return method; } diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java index 6b5606c237e..eaddf81b5a6 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateBuilder.java @@ -38,7 +38,7 @@ */ public class CreateBuilder extends JavaTransformer { - public static final String IMPLICIT_CREATE = ""; + public static final String IMPLICIT_CREATE = "$create"; public CreateBuilder(TransformationPipelineServices services) { super(services); diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java index 73307471493..4d6f9ee0fc8 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/CreateObjectBuilder.java @@ -38,7 +38,7 @@ */ public class CreateObjectBuilder extends JavaTransformer { - public static final String IMPLICIT_OBJECT_CREATE = ""; + public static final String IMPLICIT_OBJECT_CREATE = "$createObject"; public static final String NEW_OBJECT_VAR_NAME = "__NEW__"; private final HashMap, SimpleName> class2SimpleName; diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java index dc9e749c6e4..718c3ece11c 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/transformations/pipeline/PipelineConstants.java @@ -21,5 +21,5 @@ public interface PipelineConstants { String VIRTUAL_CLASS_FOR_PARSING = "$virtual_class_for_parsing"; String IMPLICIT_OBJECT_PREPARE = "$prepare"; String IMPLICIT_OBJECT_PREPARE_ENTER = "$prepareEnter"; - String IMPLICIT_INSTANCE_ALLOCATE = ""; + String IMPLICIT_INSTANCE_ALLOCATE = "$allocate"; } diff --git a/key/key.java/src/test/java/KeyJavaPipelineTest.java b/key/key.java/src/test/java/KeyJavaPipelineTest.java index 842d002e33f..c1d2ac734de 100644 --- a/key/key.java/src/test/java/KeyJavaPipelineTest.java +++ b/key/key.java/src/test/java/KeyJavaPipelineTest.java @@ -1,6 +1,12 @@ -import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.key.KeyPassiveExpression; +import com.github.javaparser.printer.DefaultPrettyPrinter; +import com.github.javaparser.printer.DefaultPrettyPrinterVisitor; +import com.github.javaparser.printer.Printer; +import com.github.javaparser.printer.SourcePrinter; +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration; +import com.github.javaparser.printer.configuration.PrinterConfiguration; import de.uka.ilkd.key.java.JavaService; import de.uka.ilkd.key.java.transformations.KeyJavaPipeline; import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; @@ -57,6 +63,9 @@ private static class DebugOutputTransformer extends JavaTransformer { final File outputFolder; final Set alreadyWritten = new HashSet<>(); private static final Logger LOGGER = LoggerFactory.getLogger(DebugOutputTransformer.class); + private Printer myPrinter = new DefaultPrettyPrinter( + MyPrintVisitor::new, + new DefaultPrinterConfiguration()); public DebugOutputTransformer(File s, TransformationPipelineServices services) { @@ -73,6 +82,7 @@ public void apply(TypeDeclaration td) { if (!alreadyWritten.contains(file)) { alreadyWritten.add(file); try { + unit.printer(myPrinter); Files.writeString(file.toPath(), unit.toString()); } catch (IOException e) { LOGGER.error(e.getMessage(), e); @@ -81,4 +91,21 @@ public void apply(TypeDeclaration td) { } } } + + private static class MyPrintVisitor extends DefaultPrettyPrinterVisitor { + public MyPrintVisitor(PrinterConfiguration configuration) { + super(configuration); + } + + public MyPrintVisitor(PrinterConfiguration configuration, SourcePrinter printer) { + super(configuration, printer); + } + + @Override + public void visit(KeyPassiveExpression n, Void arg) { + printer.print("@("); + n.getExpr().accept(this, arg); + printer.print(")"); + } + } } From 08fb8549dc75fd251f5009e29c2358c605237ec7 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 20 Feb 2022 14:15:28 +0100 Subject: [PATCH 003/225] add assertions and oracle --- key/key.java/build.gradle | 7 +- .../expected/01_JMLTransformer/Test.java | 24 +++ .../expected/02_ImplicitFieldAdder/Test.java | 48 ++++++ .../Test.java | 48 ++++++ .../04_ConstructorNormalformBuilder/Test.java | 48 ++++++ .../Test.java | 54 +++++++ .../06_ClassInitializeMethodBuilder/Test.java | 110 +++++++++++++ .../07_PrepareObjectBuilder/Test.java | 122 +++++++++++++++ .../expected/08_CreateBuilder/Test.java | 134 ++++++++++++++++ .../expected/09_CreateObjectBuilder/Test.java | 148 ++++++++++++++++++ .../10_LocalClassTransformation/Test.java | 148 ++++++++++++++++++ .../Test.java | 148 ++++++++++++++++++ .../src/test/java/KeyJavaPipelineTest.java | 58 +++++-- 13 files changed, 1078 insertions(+), 19 deletions(-) create mode 100644 key/key.java/pipelineTests/simple/expected/01_JMLTransformer/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/02_ImplicitFieldAdder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/03_InstanceAllocationMethodBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/04_ConstructorNormalformBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/05_ClassPreparationMethodBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/06_ClassInitializeMethodBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/07_PrepareObjectBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/08_CreateBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/09_CreateObjectBuilder/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/10_LocalClassTransformation/Test.java create mode 100644 key/key.java/pipelineTests/simple/expected/11_ConstantStringExpressionEvaluator/Test.java diff --git a/key/key.java/build.gradle b/key/key.java/build.gradle index d685bd423d2..c99ec5ed3a9 100644 --- a/key/key.java/build.gradle +++ b/key/key.java/build.gradle @@ -4,8 +4,9 @@ dependencies { api project(':key.util') api project(':key.core') - api 'com.github.javaparser:javaparser-core:3.23.2-SNAPSHOT' - api 'com.github.javaparser:javaparser-core-serialization:3.23.2-SNAPSHOT' - api 'com.github.javaparser:javaparser-symbol-solver-core:3.23.2-SNAPSHOT' + api 'com.github.javaparser:javaparser-core:3.24.1-SNAPSHOT' + api 'com.github.javaparser:javaparser-core-serialization:3.24.1-SNAPSHOT' + api 'com.github.javaparser:javaparser-symbol-solver-core:3.24.1-SNAPSHOT' + testImplementation("com.google.truth:truth:1.1.3") } \ No newline at end of file diff --git a/key/key.java/pipelineTests/simple/expected/01_JMLTransformer/Test.java b/key/key.java/pipelineTests/simple/expected/01_JMLTransformer/Test.java new file mode 100644 index 00000000000..dba29c488a0 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/01_JMLTransformer/Test.java @@ -0,0 +1,24 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } +} diff --git a/key/key.java/pipelineTests/simple/expected/02_ImplicitFieldAdder/Test.java b/key/key.java/pipelineTests/simple/expected/02_ImplicitFieldAdder/Test.java new file mode 100644 index 00000000000..369eb5c5a0b --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/02_ImplicitFieldAdder/Test.java @@ -0,0 +1,48 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} diff --git a/key/key.java/pipelineTests/simple/expected/03_InstanceAllocationMethodBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/03_InstanceAllocationMethodBuilder/Test.java new file mode 100644 index 00000000000..369eb5c5a0b --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/03_InstanceAllocationMethodBuilder/Test.java @@ -0,0 +1,48 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} diff --git a/key/key.java/pipelineTests/simple/expected/04_ConstructorNormalformBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/04_ConstructorNormalformBuilder/Test.java new file mode 100644 index 00000000000..369eb5c5a0b --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/04_ConstructorNormalformBuilder/Test.java @@ -0,0 +1,48 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; +} diff --git a/key/key.java/pipelineTests/simple/expected/05_ClassPreparationMethodBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/05_ClassPreparationMethodBuilder/Test.java new file mode 100644 index 00000000000..2667e04b7f6 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/05_ClassPreparationMethodBuilder/Test.java @@ -0,0 +1,54 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } +} diff --git a/key/key.java/pipelineTests/simple/expected/06_ClassInitializeMethodBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/06_ClassInitializeMethodBuilder/Test.java new file mode 100644 index 00000000000..c54313f27fc --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/06_ClassInitializeMethodBuilder/Test.java @@ -0,0 +1,110 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } +} diff --git a/key/key.java/pipelineTests/simple/expected/07_PrepareObjectBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/07_PrepareObjectBuilder/Test.java new file mode 100644 index 00000000000..43248ead7e3 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/07_PrepareObjectBuilder/Test.java @@ -0,0 +1,122 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } +} diff --git a/key/key.java/pipelineTests/simple/expected/08_CreateBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/08_CreateBuilder/Test.java new file mode 100644 index 00000000000..af1464d32c7 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/08_CreateBuilder/Test.java @@ -0,0 +1,134 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public Test $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public SubClass $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } +} diff --git a/key/key.java/pipelineTests/simple/expected/09_CreateObjectBuilder/Test.java b/key/key.java/pipelineTests/simple/expected/09_CreateObjectBuilder/Test.java new file mode 100644 index 00000000000..15e129f0927 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/09_CreateObjectBuilder/Test.java @@ -0,0 +1,148 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public Test $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static Test $createObject() { + Test __NEW__; + __NEW__ = Test.$allocate(); + + return __NEW__; + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public SubClass $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static SubClass $createObject() { + SubClass __NEW__; + __NEW__ = SubClass.$allocate(); + + return __NEW__; + } +} diff --git a/key/key.java/pipelineTests/simple/expected/10_LocalClassTransformation/Test.java b/key/key.java/pipelineTests/simple/expected/10_LocalClassTransformation/Test.java new file mode 100644 index 00000000000..15e129f0927 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/10_LocalClassTransformation/Test.java @@ -0,0 +1,148 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public Test $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static Test $createObject() { + Test __NEW__; + __NEW__ = Test.$allocate(); + + return __NEW__; + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public SubClass $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static SubClass $createObject() { + SubClass __NEW__; + __NEW__ = SubClass.$allocate(); + + return __NEW__; + } +} diff --git a/key/key.java/pipelineTests/simple/expected/11_ConstantStringExpressionEvaluator/Test.java b/key/key.java/pipelineTests/simple/expected/11_ConstantStringExpressionEvaluator/Test.java new file mode 100644 index 00000000000..15e129f0927 --- /dev/null +++ b/key/key.java/pipelineTests/simple/expected/11_ConstantStringExpressionEvaluator/Test.java @@ -0,0 +1,148 @@ +public class Test { + + public static int abc; + + static { + // should be resolved to 2 + abc = 1 + 1; + } + + public int memberVar; + + { + memberVar = 42; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(java.lang.Object.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public Test $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static Test $createObject() { + Test __NEW__; + __NEW__ = Test.$allocate(); + + return __NEW__; + } +} + +public class SubClass extends Test { + + public int memberVar; + + { + memberVar = 41; + } + + @javax.annotation.processing.Generated() + static private boolean $classInitializationInProgress; + + @javax.annotation.processing.Generated() + static private boolean $classErroneous; + + @javax.annotation.processing.Generated() + static private boolean $classInitialized; + + @javax.annotation.processing.Generated() + static private boolean $classPrepared; + + static private void $clprepare() { + } + + static public void $clinit() { + if (!@($classInitialized)) { + if (!@($classInitializationInProgress)) { + if (!@(this.$classPrepared)) { + @($clprepare()); + } + if (@($classErroneous)) { + throw new java.lang.NoClassDefFoundError(); + } + @($classInitializationInProgress) = true; + try { + @(Test.$clinit()); + } catch (java.lang.Error err) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw err; + } catch (java.lang.Throwable twa) { + @($classInitializationInProgress) = false; + @($classErroneous) = true; + throw new java.lang.ExceptionInInitializerError(twa); + } + @($classInitializationInProgress) = false; + @($classErroneous) = false; + @($classInitialized) = true; + } + } + } + + protected void $prepare() { + } + + private void $prepareEnter() { + } + + public SubClass $create() { + this.$initialized = false; + $prepareEnter(); + return this; + } + + public static SubClass $createObject() { + SubClass __NEW__; + __NEW__ = SubClass.$allocate(); + + return __NEW__; + } +} diff --git a/key/key.java/src/test/java/KeyJavaPipelineTest.java b/key/key.java/src/test/java/KeyJavaPipelineTest.java index c1d2ac734de..8f66cd03d6b 100644 --- a/key/key.java/src/test/java/KeyJavaPipelineTest.java +++ b/key/key.java/src/test/java/KeyJavaPipelineTest.java @@ -1,17 +1,20 @@ +import com.github.javaparser.Problem; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.TypeDeclaration; import com.github.javaparser.ast.key.KeyPassiveExpression; import com.github.javaparser.printer.DefaultPrettyPrinter; import com.github.javaparser.printer.DefaultPrettyPrinterVisitor; import com.github.javaparser.printer.Printer; -import com.github.javaparser.printer.SourcePrinter; import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration; import com.github.javaparser.printer.configuration.PrinterConfiguration; +import com.google.common.truth.Truth; import de.uka.ilkd.key.java.JavaService; import de.uka.ilkd.key.java.transformations.KeyJavaPipeline; import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,24 +22,29 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Stream; /** * @author Alexander Weigl * @version 1 (19.02.22) */ -public class KeyJavaPipelineTest { +class KeyJavaPipelineTest { public KeyJavaPipeline createPipelineTest(File testFolder) throws FileNotFoundException { var js = new JavaService(Collections.singleton(testFolder)); var inputFolder = new File(testFolder, "input"); final var jp = js.createJavaParser(); var files = inputFolder.listFiles(); var cu = new ArrayList(); - for (File it : files) { + for (File it : Objects.requireNonNull(files)) { var r = jp.parse(it); + if (!r.isSuccessful()) { + for (Problem problem : r.getProblems()) { + System.out.println(problem); + } + throw new IllegalStateException(); + } var c = r.getResult().get(); cu.add(c); } @@ -53,17 +61,39 @@ public KeyJavaPipeline createPipelineTest(File testFolder) throws FileNotFoundEx return kjp2; } - @Test - void simple() throws FileNotFoundException { - var pt = createPipelineTest(new File("pipelineTests/simple")); + @TestFactory + Stream simple() throws IOException { + return generatePipelineTests(new File("pipelineTests/simple").getAbsoluteFile()); + } + + private Stream generatePipelineTests(File testFolder) throws IOException { + var pt = createPipelineTest(testFolder); pt.apply(); + var expected = new File(testFolder, "expected").toPath(); + var actual = new File(testFolder, "actual").toPath(); + + return Files.walk(expected) + .filter(Files::isRegularFile) + .map(it -> + DynamicTest.dynamicTest(it.toString(), () -> checkEqualFile(it, expected, actual))); + } + + private void checkEqualFile(Path expectedFile, Path expectedFolder, Path actualFolder) throws IOException { + var actualFile = actualFolder.resolve(expectedFolder.relativize(expectedFile)); + if (!Files.exists(actualFile)) { + Assertions.fail("Actual file " + actualFile + " does not exists."); + } + var expected = Files.readString(expectedFile); + var actual = Files.readString(actualFile); + + Truth.assertThat(actual).isEqualTo(expected); } private static class DebugOutputTransformer extends JavaTransformer { final File outputFolder; final Set alreadyWritten = new HashSet<>(); private static final Logger LOGGER = LoggerFactory.getLogger(DebugOutputTransformer.class); - private Printer myPrinter = new DefaultPrettyPrinter( + private final Printer myPrinter = new DefaultPrettyPrinter( MyPrintVisitor::new, new DefaultPrinterConfiguration()); @@ -97,10 +127,6 @@ public MyPrintVisitor(PrinterConfiguration configuration) { super(configuration); } - public MyPrintVisitor(PrinterConfiguration configuration, SourcePrinter printer) { - super(configuration, printer); - } - @Override public void visit(KeyPassiveExpression n, Void arg) { printer.print("@("); From 5fc01aca202bd4c29218d3f33325b5169417b1cb Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Mar 2022 13:26:02 +0100 Subject: [PATCH 004/225] investigations of recoder-related classes --- .../src/main/java/de/uka/ilkd/key/java/JavaInfo.java | 5 ++--- .../java/de/uka/ilkd/key/java/KeYProgModelInfo.java | 10 ++++++---- .../main/java/de/uka/ilkd/key/java/JavaService.java | 9 +++++++-- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaInfo.java index d9c0f7ab757..727e974f393 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaInfo.java @@ -30,11 +30,10 @@ import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; - -import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import recoder.service.KeYCrossReferenceSourceInfo; + +import java.util.*; /** * an instance serves as representation of a Java model underlying a DL diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYProgModelInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYProgModelInfo.java index b56f67f484b..87bad5e080e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYProgModelInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYProgModelInfo.java @@ -33,6 +33,7 @@ import recoder.abstraction.Constructor; import recoder.java.CompilationUnit; +import javax.annotation.Nonnull; import java.util.*; public class KeYProgModelInfo { @@ -137,9 +138,10 @@ public ImmutableList getAllProgramMethods(KeYJavaType kjt) { return result; } + @Nonnull private List getRecoderTypes(ImmutableList types) { if (types == null) { - return null; + return Collections.emptyList(); } final ArrayList tl = new ArrayList<>(types.size()); @@ -224,7 +226,7 @@ public String getFullName(KeYJavaType t) { return rt.getFullName(); } - public recoder.abstraction.Type getType(TypeReference tr) { + private recoder.abstraction.Type getType(TypeReference tr) { recoder.abstraction.Type result; if (tr instanceof TypeRef) { result = (recoder.abstraction.Type) @@ -394,7 +396,7 @@ private List getRecoderConstructors(K * @param signature the statical type signature of a callee. */ - public ImmutableList getMethods(KeYJavaType ct, String m, + private ImmutableList getMethods(KeYJavaType ct, String m, ImmutableList signature, KeYJavaType context) { List rml = getRecoderMethods(ct, m, signature, context); @@ -879,7 +881,7 @@ private boolean isDeclaringInterface(recoder.abstraction.ClassType ct, return false; } - public void putImplicitMethod(IProgramMethod m, KeYJavaType t) { + private void putImplicitMethod(IProgramMethod m, KeYJavaType t) { Map map = implicits.get(t); if (map == null) { map = new LinkedHashMap<>(); diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java index 627d7c0ec7d..fee3643b139 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java @@ -11,7 +11,6 @@ import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import recoder.util.Debug; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -22,6 +21,12 @@ import java.util.List; /** + * Facade for the JavaParser. + *

+ * This class allows you to configure a classpath, and source path. + * To parse Java source files, to process them in the Java2Java pipeline + * and to have a proper symbol resolution. + * * @author Alexander Weigl * @version 1 (19.02.22) */ @@ -50,8 +55,8 @@ public JavaParser createJavaParser() { private ParserConfiguration getConfiguration() { if (config == null) { config = new ParserConfiguration(); - config.setSymbolResolver(getSymbolResolver()); } + config.setSymbolResolver(getSymbolResolver()); return config; } From 46123067ef6aab7d9c094301bed4412e02a36c81 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Mar 2022 13:26:28 +0100 Subject: [PATCH 005/225] housekeeping * pre-allocation sizes * logging --- .../uka/ilkd/key/java/KeYRecoderMapping.java | 29 +++++++++++-------- .../java/de/uka/ilkd/key/proof/Proof.java | 1 + .../main/java/de/uka/ilkd/key/core/Log.java | 19 ++++++++---- .../main/java/de/uka/ilkd/key/core/Main.java | 19 +++++------- key/key.ui/src/main/resources/logback.xml | 2 ++ 5 files changed, 41 insertions(+), 29 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java index 76f36f711ab..5c34bd574fc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java @@ -20,10 +20,12 @@ import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.util.Debug; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class KeYRecoderMapping{ + public static final Logger LOGGER = LoggerFactory.getLogger(KeYRecoderMapping.class); /** have special classes been parsed in */ @@ -40,10 +42,10 @@ public class KeYRecoderMapping{ /** a pseudo super class for all arrays used to declare length */ private KeYJavaType superArrayType=null; - + public KeYRecoderMapping() { - this.map = new LinkedHashMap<>(); - this.revMap = new LinkedHashMap<>(); + this.map = new LinkedHashMap<>(4096); + this.revMap = new LinkedHashMap<>(4096); } @@ -110,22 +112,25 @@ public recoder.ModelElement toRecoder(ModelElement pe) { public void put(Object rec, Object key) { Object formerValue = map.put(rec, key); - Debug.assertTrue(formerValue == null, + Debug.assertTrue(formerValue == null, "keyrecodermapping: duplicate registration of type:", key); revMap.put(key, rec); + LOGGER.warn("Size of rec2key: {} entries", map.size()); } public boolean mapped(Object rec) { return map.containsKey(rec); } - + public Set elemsKeY() { - return revMap.keySet(); + LOGGER.error("Size of rec2key: {} entries", map.size()); + + return revMap.keySet(); } public Set elemsRec() { - return map.keySet(); + return map.keySet(); } public void setSuperArrayType(KeYJavaType superArrayType) { @@ -136,7 +141,7 @@ public KeYJavaType getSuperArrayType() { return this.superArrayType; } - + @SuppressWarnings("unchecked") public KeYRecoderMapping copy() { return new KeYRecoderMapping((HashMap)map.clone(), @@ -150,7 +155,7 @@ public KeYRecoderMapping copy() { * some 'java.lang' classes. These are parsed in using method * parseSpecial of {@link Recoder2KeY}. To avoid multiple readings * this method indicates whether the special have been parsed in or - * not. + * not. * @return true if special classes have been parsed in */ public boolean parsedSpecial() { @@ -158,9 +163,9 @@ public boolean parsedSpecial() { } public int size(){ - return map.size(); + return map.size(); } - + /** * As long as we do not support lemmata we need the source code of diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/proof/Proof.java b/key/key.core/src/main/java/de/uka/ilkd/key/proof/Proof.java index 0db12bbe70d..6623f345d11 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/proof/Proof.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/proof/Proof.java @@ -311,6 +311,7 @@ public void dispose() { ruleAppListenerList = null; listenerList = null; disposed = true; + userData = null; fireProofDisposed(new ProofDisposedEvent(this)); } diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java index 64c5aad5d8d..eef7a5a8922 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java @@ -1,6 +1,9 @@ package de.uka.ilkd.key.core; import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.filter.ThresholdFilter; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; import de.uka.ilkd.key.ui.Verbosity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,21 +28,27 @@ public class Log { public static void configureLogging(int verbosity) { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + Appender consoleAppender = root.getAppender("STDOUT"); + var filter = new ThresholdFilter(); + consoleAppender.addFilter(filter); switch (verbosity) { case Verbosity.TRACE: - root.setLevel(Level.TRACE); + filter.setLevel("TRACE"); break; case Verbosity.DEBUG: - root.setLevel(Level.DEBUG); + filter.setLevel("DEBUG"); break; case Verbosity.INFO: - root.setLevel(Level.INFO); + filter.setLevel("INFO"); break; case Verbosity.NORMAL: - root.setLevel(Level.ERROR); + filter.setLevel("ERROR"); break; case Verbosity.SILENT: - root.setLevel(Level.OFF); + filter.setLevel("OFF"); + break; + default: + filter.setLevel("WARN"); break; } } diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java index 6e6a86f05a5..a5ffbe6e8ef 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java @@ -235,18 +235,17 @@ private static void logInformation() { LOGGER.debug("OS: {}", System.getProperty("java.os")); LOGGER.debug("Hardware: {}", System.getProperty("java.hw")); Runtime rt = Runtime.getRuntime(); - LOGGER.debug("Total memory: " + (rt.totalMemory() / 1048576.0) + " MB"); - LOGGER.debug("Maximum memory: " + (rt.maxMemory() / 1048576.0) + " MB"); - LOGGER.debug("Free memory: " + (rt.freeMemory() / 1048576.0) + " MB"); - LOGGER.debug("Available processors: " + rt.availableProcessors()); + LOGGER.debug("Total memory: {} MB", (rt.totalMemory() / 1048576.0)); + LOGGER.debug("Maximum memory: {} MB" , (rt.maxMemory() / 1048576.0)); + LOGGER.debug("Free memory: {} MB", (rt.freeMemory() / 1048576.0)); + LOGGER.debug("Available processors: {}", rt.availableProcessors()); } public static void loadCommandLineFiles(AbstractMediatorUserInterfaceControl ui, List fileArguments) { if (!fileArguments.isEmpty()) { ui.setMacro(autoMacro); ui.setSaveOnly(saveAllContracts); - for (int i = 0; i < fileArguments.size(); i++) { - File f = fileArguments.get(i); + for (File f : fileArguments) { ui.loadProblem(f); } if (ui instanceof ConsoleUserInterfaceControl) { @@ -502,11 +501,7 @@ public static void evaluateOptions(CommandLine cl) { */ public static void setEnabledExperimentalFeatures(boolean state) { experimentalMode = state; - /*String configuration = experimentalMode ? LOGGING_CONFIG_EXPERIMENTAL : LOGGING_CONFIG_DEFAULT; - try (final InputStream in = Main.class.getResourceAsStream(configuration)) { - } catch (IOException e) { - //LOGGER.log(Level.INFO, e.getMessage(), e); - }*/ + LOGGER.info("Experimental Features: {}", state); } public static boolean isExperimentalMode() { @@ -517,7 +512,7 @@ public static boolean isExperimentalMode() { * Print a header text on to the console. */ private static void printHeader() { - LOGGER.info("KeY Version " + KeYConstants.VERSION); + LOGGER.info("KeY Version {}", KeYConstants.VERSION); LOGGER.info(KeYConstants.COPYRIGHT); LOGGER.info("KeY is protected by the GNU General Public License"); } diff --git a/key/key.ui/src/main/resources/logback.xml b/key/key.ui/src/main/resources/logback.xml index b0eb99ed491..85307f95245 100644 --- a/key/key.ui/src/main/resources/logback.xml +++ b/key/key.ui/src/main/resources/logback.xml @@ -12,9 +12,11 @@ [%date{HH:mm:ss.SSS}] %highlight(%-5level) %cyan(%logger{0}) - %msg%ex%n + From 7ef10fb133ab115e815d9e0603f8c969fe295bc5 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Mar 2022 22:33:32 +0100 Subject: [PATCH 006/225] try to write a rec2key adapter for Javaparser --- .../key/java/JavaReduxFileCollection.java | 108 +- .../uka/ilkd/key/java/KeYRecoderMapping.java | 142 +-- .../ilkd/key/java/PackageSpecification.java | 15 +- .../key/util/DirectoryFileCollection.java | 6 + .../de/uka/ilkd/key/util/FileCollection.java | 11 +- .../uka/ilkd/key/util/ZipFileCollection.java | 12 + .../ilkd/key/util/parsing/BuildingIssue.java | 43 +- .../de/uka/ilkd/key/java/JP2KeyConverter.java | 958 ++++++++++++++++ .../ilkd/key/java/JP2KeyTypeConverter.java | 12 + .../java/de/uka/ilkd/key/java/JPContext.java | 26 + .../uka/ilkd/key/java/JavaParserFactory.java | 27 + .../de/uka/ilkd/key/java/JavaService.java | 1008 ++++++++++++++++- .../de/uka/ilkd/key/java/KeyJPMapping.java | 170 +++ .../src/test/java/KeyJavaPipelineTest.java | 76 +- .../main/java/de/uka/ilkd/key/core/Log.java | 28 +- .../main/java/de/uka/ilkd/key/core/Main.java | 166 +-- .../key/ui/ConsoleUserInterfaceControl.java | 144 ++- .../java/de/uka/ilkd/key/ui/Verbosity.java | 8 +- .../java/org/key_project/util/ExtList.java | 91 +- .../org/key_project/util/java/IOUtil.java | 2 +- 20 files changed, 2600 insertions(+), 453 deletions(-) create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyTypeConverter.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/JPContext.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/JavaParserFactory.java create mode 100644 key/key.java/src/main/java/de/uka/ilkd/key/java/KeyJPMapping.java diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaReduxFileCollection.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaReduxFileCollection.java index c82cd286589..c6c34799552 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaReduxFileCollection.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaReduxFileCollection.java @@ -13,37 +13,36 @@ package de.uka.ilkd.key.java; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import recoder.io.DataLocation; import de.uka.ilkd.key.java.recoderext.URLDataLocation; import de.uka.ilkd.key.proof.init.Profile; import de.uka.ilkd.key.proof.io.consistency.FileRepo; import de.uka.ilkd.key.util.FileCollection; import de.uka.ilkd.key.util.KeYResourceManager; +import recoder.io.DataLocation; + +import java.io.*; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.stream.Stream; /** * This is a special {@link FileCollection} which allows to retrieve the * internally stored java boot sources and to iterate over them. - * + * *

* The resources are stored in the binaries. We use the * {@link KeYResourceManager} to find the resources. - * + * *

* There is a text file whose name is given by * {@link de.uka.ilkd.key.proof.init.Profile#getInternalClasslistFilename()} * which enumerates all java files that have to be read. - * + * * @author mulbrich */ public class JavaReduxFileCollection implements FileCollection { @@ -58,7 +57,7 @@ public class JavaReduxFileCollection implements FileCollection { * The resource location */ private String resourceLocation; - + /** * This list stores all resources to be retrieved. It is fed by the * constructor. @@ -67,51 +66,45 @@ public class JavaReduxFileCollection implements FileCollection { /** * Instantiates a new file collection. - * + *

* The list of resources is retreived and interpreted. The resources * themselves are not yet read. - * - * @throws IOException - * if access to the resources fails + * + * @throws IOException if access to the resources fails */ public JavaReduxFileCollection(Profile profile) throws IOException { + resourceLocation = JAVA_SRC_DIR; + if (!profile.getInternalClassDirectory().isEmpty()) { + resourceLocation += "/" + profile + .getInternalClassDirectory(); + } + String resourceString = resourceLocation + "/" + + profile + .getInternalClasslistFilename(); - resourceLocation = JAVA_SRC_DIR; - - if (!profile.getInternalClassDirectory().isEmpty()) { - resourceLocation += "/" + profile - .getInternalClassDirectory(); - } - String resourceString = resourceLocation + "/" - + profile - .getInternalClasslistFilename(); + URL jlURL = KeYResourceManager.getManager().getResourceFile( + Recoder2KeY.class, resourceString); - URL jlURL = KeYResourceManager.getManager().getResourceFile( - Recoder2KeY.class, resourceString); - if (jlURL == null) { throw new FileNotFoundException("Resource " + resourceString + " cannot be opened."); } - BufferedReader r = new BufferedReader(new InputStreamReader(jlURL - .openStream())); - - for (String jl = r.readLine(); (jl != null); jl = r.readLine()) { - // ignore comments and empty lines - if ((jl.length() == 0) || (jl.charAt(0) == '#')) { - continue; + try (BufferedReader r = new BufferedReader(new InputStreamReader(jlURL.openStream()))) { + for (String jl = r.readLine(); (jl != null); jl = r.readLine()) { + // ignore comments and empty lines + if ((jl.length() == 0) || (jl.charAt(0) == '#')) { + continue; + } + resources.add(jl); } - - resources.add(jl); } - r.close(); } /** * {@inheritDoc} - * + *

* This class only supports walker for a single file type: .java */ public Walker createWalker(String extension) throws IOException { @@ -126,7 +119,7 @@ public Walker createWalker(String extension) throws IOException { /** * {@inheritDoc} - * + *

* This class only supports walker for a single file type: .java */ public Walker createWalker(String[] extensions) throws IOException { @@ -139,6 +132,12 @@ public Walker createWalker(String[] extensions) throws IOException { } + public Stream getResources() { + return resources.stream() + .map(it -> KeYResourceManager.getManager().getResourceFile( + Recoder2KeY.class, resourceLocation + "/" + it)); + } + /* * The Class Walker wraps a string iterator and creates URL, streams and * DataLocation elements on demand. @@ -160,7 +159,7 @@ private class Walker implements FileCollection.Walker { */ private URL currentURL = null; - + private Walker(Iterator iterator) { this.iterator = iterator; } @@ -168,11 +167,20 @@ private Walker(Iterator iterator) { public DataLocation getCurrentDataLocation() throws NoSuchElementException { if (currentURL == null) - throw new NoSuchElementException("Location of "+current+" not found."); + throw new NoSuchElementException("Location of " + current + " not found."); return new URLDataLocation(currentURL); } + @Override + public Path getCurrentLocation() throws NoSuchElementException { + try { + return Path.of(currentURL.toURI()); + } catch (URISyntaxException e) { + return null; + } + } + public String getCurrentName() throws NoSuchElementException { return current; } @@ -187,9 +195,7 @@ public InputStream openCurrent() throws IOException, throw new NoSuchElementException(); if (currentURL == null) { - throw new FileNotFoundException("cannot find " - + resourceLocation - + "/" + current); + throw new FileNotFoundException("cannot find " + resourceLocation + "/" + current); } return currentURL.openStream(); @@ -213,13 +219,13 @@ public boolean step() { } current = iterator.next(); - + final String currentFileName = current.replace('.', '/').concat(".java"); // may be null! currentURL = KeYResourceManager.getManager().getResourceFile( Recoder2KeY.class, resourceLocation + "/" + currentFileName); - + return true; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java index 5c34bd574fc..5da923eff90 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYRecoderMapping.java @@ -14,112 +14,124 @@ package de.uka.ilkd.key.java; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Set; - import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.util.Debug; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Set; + -public class KeYRecoderMapping{ +public class KeYRecoderMapping { public static final Logger LOGGER = LoggerFactory.getLogger(KeYRecoderMapping.class); - /** have special classes been parsed in */ + /** + * have special classes been parsed in + */ private boolean parsedSpecial = false; - /** maps a recoder programelement (or something similar, e.g. Type) - * to the KeY-equivalent - */ + /** + * maps a recoder programelement (or something similar, e.g. Type) + * to the KeY-equivalent + */ private HashMap map; - /** maps a KeY programelement to the Recoder-equivalent */ + /** + * maps a KeY programelement to the Recoder-equivalent + */ private HashMap revMap; - /** a pseudo super class for all arrays used to declare length */ - private KeYJavaType superArrayType=null; + /** + * a pseudo super class for all arrays used to declare length + */ + private KeYJavaType superArrayType = null; public KeYRecoderMapping() { - this.map = new LinkedHashMap<>(4096); - this.revMap = new LinkedHashMap<>(4096); + this.map = new LinkedHashMap<>(4096); + this.revMap = new LinkedHashMap<>(4096); } /** - * creates a KeYRecoderMapping object. - * Used for cloning and testing. - * @param map a HashMap mapping ProgramElements in Recoder to - * ProgramElements in KeY - * @param revMap the reverse map (KeY->Recoder) - * @param parsedSpecial boolean indicating if the special classes have been parsed in - */ + * creates a KeYRecoderMapping object. + * Used for cloning and testing. + * + * @param map a HashMap mapping ProgramElements in Recoder to + * ProgramElements in KeY + * @param revMap the reverse map (KeY->Recoder) + * @param parsedSpecial boolean indicating if the special classes have been parsed in + */ KeYRecoderMapping(HashMap map, HashMap revMap, - KeYJavaType superArrayType, - boolean parsedSpecial) { - this.map = map; - this.revMap = revMap; + KeYJavaType superArrayType, + boolean parsedSpecial) { + this.map = map; + this.revMap = revMap; this.superArrayType = superArrayType; - this.parsedSpecial = parsedSpecial; + this.parsedSpecial = parsedSpecial; } /** - * returns a matching ProgramElement (KeY) to a given - * ProgramElement (Recoder) - * @param pe a recoder.java.ProgramElement - */ + * returns a matching ProgramElement (KeY) to a given + * ProgramElement (Recoder) + * + * @param pe a recoder.java.ProgramElement + */ public ProgramElement toKeY(recoder.java.ProgramElement pe) { - return (ProgramElement)map.get(pe); + return (ProgramElement) map.get(pe); } /** - * returns a matching ModelElement (KeY) to a given recoder.ModelElement - * @param pe a recoder.ModelElement - */ + * returns a matching ModelElement (KeY) to a given recoder.ModelElement + * + * @param pe a recoder.ModelElement + */ public ModelElement toKeY(recoder.ModelElement pe) { - return (ModelElement)map.get(pe); + return (ModelElement) map.get(pe); } /** - * returns the Recoder-equivalent to a given ProgramElement (KeY). - * If there's no RecodeR equivalent to program element pe, an - * assertion failure "Program Element not known" is emitted. - * @param pe a JavaProgramElement - */ + * returns the Recoder-equivalent to a given ProgramElement (KeY). + * If there's no RecodeR equivalent to program element pe, an + * assertion failure "Program Element not known" is emitted. + * + * @param pe a JavaProgramElement + */ public recoder.java.ProgramElement toRecoder(ProgramElement pe) { - Object res=revMap.get(pe); - Debug.assertTrue(res!=null, "Program Element not known", pe); - return (recoder.java.ProgramElement)res; + Object res = revMap.get(pe); + Debug.assertTrue(res != null, "Program Element not known", pe); + return (recoder.java.ProgramElement) res; } /** - * returns the Recoder-equivalent to a given ModelElement (KeY). - * If there's no Recoder-equivalent to the ModelElement pe a - * debug message "Model Element not known" is printed. - * @param pe a ModelElement - */ + * returns the Recoder-equivalent to a given ModelElement (KeY). + * If there's no Recoder-equivalent to the ModelElement pe a + * debug message "Model Element not known" is printed. + * + * @param pe a ModelElement + */ public recoder.ModelElement toRecoder(ModelElement pe) { - Object res=revMap.get(pe); - Debug.assertTrue(res!=null, "Model Element not known", pe); + Object res = revMap.get(pe); + Debug.assertTrue(res != null, "Model Element not known", pe); - return (recoder.ModelElement)res; + return (recoder.ModelElement) res; } public void put(Object rec, Object key) { - Object formerValue = map.put(rec, key); - Debug.assertTrue(formerValue == null, - "keyrecodermapping: duplicate registration of type:", key); - revMap.put(key, rec); + Object formerValue = map.put(rec, key); + Debug.assertTrue(formerValue == null, + "keyrecodermapping: duplicate registration of type:", key); + revMap.put(key, rec); LOGGER.warn("Size of rec2key: {} entries", map.size()); } public boolean mapped(Object rec) { - return map.containsKey(rec); + return map.containsKey(rec); } @@ -144,10 +156,10 @@ public KeYJavaType getSuperArrayType() { @SuppressWarnings("unchecked") public KeYRecoderMapping copy() { - return new KeYRecoderMapping((HashMap)map.clone(), - (HashMap)revMap.clone(), - superArrayType, - parsedSpecial); + return new KeYRecoderMapping((HashMap) map.clone(), + (HashMap) revMap.clone(), + superArrayType, + parsedSpecial); } /** @@ -156,13 +168,14 @@ public KeYRecoderMapping copy() { * parseSpecial of {@link Recoder2KeY}. To avoid multiple readings * this method indicates whether the special have been parsed in or * not. + * * @return true if special classes have been parsed in */ public boolean parsedSpecial() { - return parsedSpecial; + return parsedSpecial; } - public int size(){ + public int size() { return map.size(); } @@ -173,11 +186,12 @@ public int size(){ * parseSpecial of {@link Recoder2KeY}. To avoid multiple readings * this method sets a flag whether the special have been parsed in or * not + * * @param b boolean indicating if the special classes have been - * parsed in + * parsed in */ public void parsedSpecial(boolean b) { - parsedSpecial = b; + parsedSpecial = b; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java index dff5c79fbf4..9420001c886 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java @@ -24,27 +24,24 @@ * taken from COMPOST and changed to achieve an immutable structure */ -public class PackageSpecification - extends JavaNonTerminalProgramElement - implements PackageReferenceContainer { - - +public class PackageSpecification extends JavaNonTerminalProgramElement implements PackageReferenceContainer { /** * Reference. */ - protected final PackageReference reference; /** * Package specification. * @param children an ExtList with children */ - public PackageSpecification(ExtList children) { - super(children); - reference=children.get(PackageReference.class); + super(children); + reference=children.get(PackageReference.class); } + public PackageSpecification(PackageReference reference) { + this.reference = reference; + } public SourceElement getLastElement() { return reference; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/DirectoryFileCollection.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/DirectoryFileCollection.java index 57fb62e8701..faa4a67f484 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/DirectoryFileCollection.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/DirectoryFileCollection.java @@ -17,6 +17,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -182,6 +183,11 @@ public String getType() { public DataLocation getCurrentDataLocation() { return new DataFileLocation(currentFile); } + + @Override + public Path getCurrentLocation() throws NoSuchElementException { + return currentFile.toPath(); + } } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/FileCollection.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/FileCollection.java index 0f960a925fa..cc5fc356d89 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/FileCollection.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/FileCollection.java @@ -15,6 +15,7 @@ import java.io.IOException; import java.io.InputStream; +import java.nio.file.Path; import java.util.NoSuchElementException; import de.uka.ilkd.key.proof.io.consistency.FileRepo; @@ -105,7 +106,15 @@ public interface Walker { * @throws NoSuchElementException if the previous call to step returned false. */ public DataLocation getCurrentDataLocation() throws NoSuchElementException; - + + /** + * + * @return + * @throws NoSuchElementException + */ + public Path getCurrentLocation() throws NoSuchElementException; + + /** * return the type of the structure that is iterated. Must return the * same value for any call diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/ZipFileCollection.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/ZipFileCollection.java index 66794b84d09..1995e1c5023 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/ZipFileCollection.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/ZipFileCollection.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; @@ -134,6 +135,17 @@ public DataLocation getCurrentDataLocation() { } return SpecDataLocation.UNKNOWN_LOCATION; // fallback } + + @Override + public Path getCurrentLocation() { + try { + URI uri = MiscTools.getZipEntryURI(zipFile, currentEntry.getName()); + return Path.of(uri); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/parsing/BuildingIssue.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/parsing/BuildingIssue.java index ba32e51d918..4105240f545 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/parsing/BuildingIssue.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/parsing/BuildingIssue.java @@ -1,22 +1,31 @@ package de.uka.ilkd.key.util.parsing; +import de.uka.ilkd.key.parser.Location; import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; + import javax.annotation.Nullable; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; -public class BuildingIssue { +public class BuildingIssue implements HasLocation { private final String message; private final int lineNumber; private final int posInLine; private final int startOffset; private final int endOffset; - private final @Nullable Throwable cause; + + @Nullable + private final Throwable cause; + @Nullable private final boolean isWarning; + private final URI location; + public BuildingIssue(String message, @Nullable Throwable cause, boolean isWarning, - int lineNumber, int posInLine, int startOffset, int endOffset) { + int lineNumber, int posInLine, int startOffset, int endOffset, URI location) { this.message = message; this.lineNumber = lineNumber; this.posInLine = posInLine; @@ -24,6 +33,7 @@ public BuildingIssue(String message, @Nullable Throwable cause, this.endOffset = endOffset; this.cause = cause; this.isWarning = isWarning; + this.location = location; } @@ -38,9 +48,19 @@ public static BuildingIssue createError(String message, @Nullable Token token, @ int posInLine = token.getCharPositionInLine(); int startOffset = token.getStartIndex(); int endOffset = token.getStopIndex(); - return new BuildingIssue(message, cause, false, lineNumber, posInLine, startOffset, endOffset); + var location = toUri(token.getTokenSource().getSourceName()); + return new BuildingIssue(message, cause, false, lineNumber, posInLine, startOffset, endOffset, location); + } + return new BuildingIssue(message, cause, false, -1, -1, -1, -1, null); + } + + private static URI toUri(String sourceName) { + try { + return new URI(sourceName); + } catch (URISyntaxException e) { + e.printStackTrace(); } - return new BuildingIssue(message, cause, false, -1, -1, -1, -1); + return null; } public static BuildingIssue createWarning(String message, @@ -54,9 +74,10 @@ public static BuildingIssue createWarning(String message, @Nullable Token token, int posInLine = token.getCharPositionInLine(); int startOffset = token.getStartIndex(); int endOffset = token.getStopIndex(); - return new BuildingIssue(message, cause, true, lineNumber, posInLine, startOffset, endOffset); + var location = toUri(token.getTokenSource().getSourceName()); + return new BuildingIssue(message, cause, true, lineNumber, posInLine, startOffset, endOffset, location); } - return new BuildingIssue(message, cause, true, -1, -1, -1, -1); + return new BuildingIssue(message, cause, true, -1, -1, -1, -1, null); } @@ -75,4 +96,10 @@ public int getStartOffset() { public int getEndOffset() { return endOffset; } + + @Nullable + @Override + public Location getLocation() throws MalformedURLException { + return new Location(location.toURL(), lineNumber, posInLine); + } } diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java new file mode 100644 index 00000000000..4099652c070 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java @@ -0,0 +1,958 @@ +package de.uka.ilkd.key.java; + +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.key.*; +import com.github.javaparser.ast.key.sv.*; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.GenericVisitorAdapter; +import com.github.javaparser.ast.visitor.Visitable; +import de.uka.ilkd.key.java.declaration.ClassDeclaration; +import de.uka.ilkd.key.java.declaration.InterfaceDeclaration; +import de.uka.ilkd.key.java.declaration.modifier.*; +import de.uka.ilkd.key.java.expression.ParenthesizedExpression; +import de.uka.ilkd.key.java.expression.PassiveExpression; +import de.uka.ilkd.key.java.expression.literal.*; +import de.uka.ilkd.key.java.expression.operator.*; +import de.uka.ilkd.key.java.reference.*; +import de.uka.ilkd.key.java.statement.*; +import de.uka.ilkd.key.logic.ProgramElementName; +import de.uka.ilkd.key.util.parsing.BuildingExceptions; +import de.uka.ilkd.key.util.parsing.BuildingIssue; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.net.URI; +import java.util.Collections; +import java.util.Optional; + +/** + * @author Alexander Weigl + * @version 1 (05.03.22) + */ +public class JP2KeyConverter { + private final Services services; + private final KeyJPMapping mapping; + + public JP2KeyConverter(Services services, KeyJPMapping mapping) { + this.services = services; + this.mapping = mapping; + } + + public CompilationUnit processCompilationUnit(com.github.javaparser.ast.CompilationUnit cu) { + return (CompilationUnit) process(cu); + } + + public Object process(Node block) { + return block.accept(new JP2KeyVisitor(mapping), null); + } +} + +class JP2KeyVisitor extends GenericVisitorAdapter { + private final KeyJPMapping mapping; + + JP2KeyVisitor(KeyJPMapping mapping) { + this.mapping = mapping; + } + + private void reportUnsupportedElement(Node n) { + var line = n.getRange().map(it -> it.begin).map(it -> it.line).orElse(-1); + var posInLine = n.getRange().map(it -> it.begin).map(it -> it.column).orElse(-1); + var loc = n.findCompilationUnit() + .flatMap(it -> it.getStorage()).map(it -> it.getPath().toUri()).orElse(null); + BuildingIssue problem = + new BuildingIssue("Unsupported element detected given by Java Parser: " + + n.getMetaModel().getTypeName() + ". Please extend the KeY-Java-Hierarchy", + null, false, line, posInLine, -1, -1, loc); + throw new BuildingExceptions(Collections.singletonList(problem)); + } + + @Override + public ModelElement visit(AnnotationDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(AnnotationMemberDeclaration n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ArrayAccessExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ArrayCreationExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ArrayInitializerExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(AssertStmt n, Void arg) { + Expression cond = (Expression) accept(n.getCheck()); + Expression message = (Expression) accepto(n.getMessage()); + return new Assert(cond, message, createPositionInfo(n)); + } + + + @Override + public ModelElement visit(AssignExpr n, Void arg) { + var children = visitChildren(n); + switch (n.getOperator()) { + case ASSIGN: + return new CopyAssignment(children); + case PLUS: + return new PlusAssignment(children); + case MINUS: + return new MinusAssignment(children); + case MULTIPLY: + return new TimesAssignment(children); + case DIVIDE: + return new DivideAssignment(children); + case BINARY_AND: + return new BinaryAndAssignment(children); + case BINARY_OR: + return new BinaryOrAssignment(children); + case XOR: + return new BinaryXOrAssignment(children); + case REMAINDER: + return new ModuloAssignment(children); + case LEFT_SHIFT: + return new ShiftLeftAssignment(children); + case SIGNED_RIGHT_SHIFT: + return new UnsignedShiftRightAssignment(children); + case UNSIGNED_RIGHT_SHIFT: + return new ShiftRightAssignment(children); + } + return null; + } + + @Override + public ModelElement visit(BinaryExpr n, Void arg) { + var children = visitChildren(n); + switch (n.getOperator()) { + case OR: + return new LogicalOr(children); + case AND: + return new LogicalAnd(children); + case BINARY_OR: + return new BinaryOr(children); + case BINARY_AND: + return new BinaryAnd(children); + case XOR: + return new BinaryXOr(children); + case EQUALS: + return new Equals(children); + case NOT_EQUALS: + return new NotEquals(children); + case LESS: + return new LessThan(children); + case GREATER: + return new GreaterThan(children); + case LESS_EQUALS: + return new LessOrEquals(children); + case GREATER_EQUALS: + return new GreaterOrEquals(children); + case LEFT_SHIFT: + return new ShiftLeft(children); + case SIGNED_RIGHT_SHIFT: + return new ShiftRight(children); + case UNSIGNED_RIGHT_SHIFT: + return new UnsignedShiftRight(children); + case PLUS: + return new Plus(children); + case MINUS: + return new Minus(children); + case MULTIPLY: + return new Times(children); + case DIVIDE: + return new Divide(children); + case REMAINDER: + return new Modulo(children); + } + return null; + } + + @Override + public ModelElement visit(BlockStmt n, Void arg) { + var children = visitChildren(n); + return new StatementBlock(children); + } + + @Override + public ModelElement visit(BooleanLiteralExpr n, Void arg) { + var children = visitChildren(n); + return new BooleanLiteral(children, n.getValue()); + } + + @Override + public ModelElement visit(BreakStmt n, Void arg) { + var children = visitChildren(n); + return new Break(children); + } + + @Override + public ModelElement visit(CastExpr n, Void arg) { + var children = visitChildren(n); + return new TypeCast(children); + } + + @Override + public ModelElement visit(CatchClause n, Void arg) { + var children = visitChildren(n); + return new Catch(children); + } + + @Override + public ModelElement visit(CharLiteralExpr n, Void arg) { + var children = visitChildren(n); + return new CharLiteral(children, n.getValue()); + } + + @Override + public ModelElement visit(ClassExpr n, Void arg) { + reportUnsupportedElement(n); + return null; + } + + @Override + public ModelElement visit(ClassOrInterfaceDeclaration n, Void arg) { + var seq = visitChildren(n); + ProgramElementName fullName = new ProgramElementName(n.getNameAsString()); + boolean isLibrary = false; //TODO weigl + if (n.isInterface()) { + return new InterfaceDeclaration(seq, fullName, isLibrary); + } else { + return new ClassDeclaration(seq, fullName, isLibrary, n.isInnerClass(), false, n.isLocalClassDeclaration()); + } + } + + private ExtList visitChildren(Node node) { + ExtList seq = new ExtList(node.getChildNodes().size()); + for (Node childNode : node.getChildNodes()) { + var element = childNode.accept(this, null); + if (element != null) { + seq.add(element); + } + } + seq.add(createPositionInfo(node)); + return seq; + } + + + private ModelElement accept(Node check) { + var a = check.accept(this, null); + mapping.put(check, a); + return a; + } + + private PositionInfo createPositionInfo(Node node) { + if (node.getRange().isEmpty()) { + return null; + } + var r = node.getRange().get(); + + URI uri = node.findCompilationUnit().flatMap(it -> + it.getStorage()).map(it -> it.getPath().toUri()).orElse(null); + Position relPos = new Position(-1, -1); + Position startPos = new Position(r.begin.line, r.begin.column); + Position endPos = new Position(r.end.line, r.end.column); + return new PositionInfo(relPos, startPos, endPos, uri); + } + + @Override + public ModelElement visit(ClassOrInterfaceType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(com.github.javaparser.ast.CompilationUnit n, Void arg) { + return new CompilationUnit((PackageSpecification) accepto(n.getPackageDeclaration()), + accepta(n.getImports()), accepta(n.getTypes())); + } + + private T[] accepta(NodeList nodes) { + return (T[]) nodes.stream().map(it -> (T) it.accept(this, null)).toArray(); + } + + @Nullable + private ModelElement accepto(Optional node) { + if (node.isEmpty()) return null; + return node.get().accept(this, null); + } + + @Override + public ModelElement visit(ConditionalExpr n, Void arg) { + var children = visitChildren(n); + return new Conditional(children); + } + + @Override + public ModelElement visit(ConstructorDeclaration n, Void arg) { + boolean parentIsInterface = false; + var children = visitChildren(n); + return new de.uka.ilkd.key.java.declaration.ConstructorDeclaration(children, parentIsInterface); + } + + @Override + public ModelElement visit(ContinueStmt n, Void arg) { + var children = visitChildren(n); + return new Continue(children); + } + + @Override + public ModelElement visit(DoStmt n, Void arg) { + var guard = accept(n.getCondition()); + var body = accept(n.getBody()); + return new Do((Expression) guard, (Statement) body, createPositionInfo(n)); + } + + @Override + public ModelElement visit(DoubleLiteralExpr n, Void arg) { + var children = visitChildren(n); + return new DoubleLiteral(children, n.getValue()); + } + + @Override + public ModelElement visit(EmptyStmt n, Void arg) { + var children = visitChildren(n); + return new EmptyStatement(children); + } + + @Override + public ModelElement visit(EnclosedExpr n, Void arg) { + var children = visitChildren(n); + return new ParenthesizedExpression(children); + } + + @Override + public ModelElement visit(EnumConstantDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(EnumDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ExplicitConstructorInvocationStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ExpressionStmt n, Void arg) { + var seq = visitChildren(n); + return (ModelElement) seq.get(0); + } + + @Override + public ModelElement visit(FieldAccessExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(FieldDeclaration n, Void arg) { + var children = visitChildren(n); + boolean parentIsInferface = false; + return new de.uka.ilkd.key.java.declaration.FieldDeclaration(children, parentIsInferface); + } + + @Override + public ModelElement visit(ForEachStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ForStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(IfStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(InitializerDeclaration n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(InstanceOfExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(IntegerLiteralExpr n, Void arg) { + var children = visitChildren(n); + return new IntLiteral(children, n.getValue()); + } + + @Override + public ModelElement visit(JavadocComment n, Void arg) { + reportUnsupportedElement(n); + return null; + } + + @Override + public ModelElement visit(LabeledStmt n, Void arg) { + var id = accept(n.getLabel()); + var stmt = accept(n.getStatement()); + return new LabeledStatement((Label) id, (Statement) stmt, createPositionInfo(n)); + } + + @Override + public ModelElement visit(LongLiteralExpr n, Void arg) { + return new LongLiteral(n.getValue()); + } + + @Override + public ModelElement visit(MarkerAnnotationExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(MemberValuePair n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(MethodCallExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(MethodDeclaration n, Void arg) { + return new de.uka.ilkd.key.java.declaration.MethodDeclaration(visitChildren(n), false, new Comment[0]); + } + + @Override + public ModelElement visit(NameExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(NormalAnnotationExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(NullLiteralExpr n, Void arg) { + return NullLiteral.NULL; + } + + @Override + public ModelElement visit(ObjectCreationExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(PackageDeclaration n, Void arg) { + if (n.getAnnotations().isNonEmpty()) reportUnsupportedElement(n); + + ProgramElementName name = translateName(n.getName()); + ReferencePrefix prefix = null;//TODO + return new PackageSpecification(new PackageReference(name, prefix)); + } + + private ProgramElementName translateName(Name name) { + return new ProgramElementName(name.asString()); + } + + @Override + public ModelElement visit(Parameter n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(PrimitiveType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(Name n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(SimpleName n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ArrayType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ArrayCreationLevel n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(IntersectionType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(UnionType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ReturnStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(SingleMemberAnnotationExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(StringLiteralExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(SuperExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(SwitchEntry n, Void arg) { + n.getLabels(); + n.getStatements(); + n.getType(); + //TODO return new Case(e, body); + return null; + } + + @Override + public ModelElement visit(SwitchStmt n, Void arg) { + return new Switch(visitChildren(n)); + } + + @Override + public ModelElement visit(SynchronizedStmt n, Void arg) { + return new Synchronized(visitChildren(n)); + } + + @Override + public ModelElement visit(ThisExpr n, Void arg) { + return new ThisReference(visitChildren(n)); + } + + @Override + public ModelElement visit(ThrowStmt n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(TryStmt n, Void arg) { + return new Try(visitChildren(n)); + } + + @Override + public ModelElement visit(LocalClassDeclarationStmt n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(LocalRecordDeclarationStmt n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(TypeParameter n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(UnaryExpr n, Void arg) { + var c = visitChildren(n); + switch (n.getOperator()) { + case PLUS: + return new Positive(c); + case MINUS: + return new Negative(c); + case PREFIX_INCREMENT: + return new PreIncrement(c); + case PREFIX_DECREMENT: + return new PreDecrement(c); + case LOGICAL_COMPLEMENT: + return new LogicalNot(c); + case BITWISE_COMPLEMENT: + return new BinaryNot(c); + case POSTFIX_INCREMENT: + return new PostIncrement(c); + case POSTFIX_DECREMENT: + return new PostDecrement(c); + } + return null; + } + + @Override + public ModelElement visit(UnknownType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(VariableDeclarationExpr n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(VariableDeclarator n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(VoidType n, Void arg) { + return null; /*TODO*/ + } + + @Override + public ModelElement visit(WhileStmt n, Void arg) { + return new While(/*TODO*/); + } + + @Override + public ModelElement visit(WildcardType n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(LambdaExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(MethodReferenceExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(TypeExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ImportDeclaration n, Void arg) { + if (n.isStatic()) { + reportUnsupportedElement(n); + } + + if (n.isAsterisk()) { + var name = translateName(n.getName()); + return new Import(new PackageReference(name, null)); + } else { + TypeReference type = null; //TODO weigl + return new Import(type, n.isAsterisk()); + } + } + + + @Override + public ModelElement visit(ModuleDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ModuleRequiresDirective n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ModuleExportsDirective n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ModuleProvidesDirective n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ModuleUsesDirective n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ModuleOpensDirective n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(UnparsableStmt n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(ReceiverParameter n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(VarType n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(Modifier n, Void arg) { + ExtList children = visitChildren(n); + var k = n.getKeyword(); + switch (k) { + case DEFAULT: + reportUnsupportedElement(n); + break; + case PUBLIC: + return new Public(children); + case PROTECTED: + return new Protected(children); + case PRIVATE: + return new Private(children); + case ABSTRACT: + return new Abstract(children); + case STATIC: + return new Static(children); + case FINAL: + return new Final(children); + case TRANSIENT: + return new Transient(children); + case VOLATILE: + return new Volatile(children); + case SYNCHRONIZED: + return new Synchronized(children); + case NATIVE: + return new Native(children); + case STRICTFP: + return new StrictFp(children); + case TRANSITIVE: + reportUnsupportedElement(n); + break; + case GHOST: + return new Ghost(children); + case MODEL: + return new Model(children); + case TWO_STATE: + return new TwoState(children); + case NO_STATE: + return new NoState(children); + } + return null; + } + + @Override + public ModelElement visit(SwitchExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(YieldStmt n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(TextBlockLiteralExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(PatternExpr n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(RecordDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(CompactConstructorDeclaration n, Void arg) { + reportUnsupportedElement(n); + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCcatchBreak n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCcatchContinue n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCcatchParameter n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCcatchReturn n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCatchAllStatement n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyEscapeExpression n, Void arg) { + //return new EscapeExpression(visitChildren(n)); + return null; + } + + @Override + public ModelElement visit(KeyExecStatement n, Void arg) { + return new Exec(visitChildren(n)); + } + + @Override + public ModelElement visit(KeyExecutionContext n, Void arg) { + return new ExecutionContext(visitChildren(n)); + } + + @Override + public ModelElement visit(KeyLoopScopeBlock n, Void arg) { + return new LoopScopeBlock(visitChildren(n)); + } + + @Override + public ModelElement visit(KeyMergePointStatement n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMethodBodyStatement n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMethodCallStatement n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMethodSignature n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyRangeExpression n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyTransactionStatement n, Void arg) { + return new TransactionStatement(n.getType().ordinal()); + } + + @Override + public ModelElement visit(KeyContextStatementBlock n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyExecCtxtSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyExpressionSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyJumpLabelSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMetaConstructExpression n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMetaConstruct n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMetaConstructType n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyMethodSignatureSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyPassiveExpression n, Void arg) { + return new PassiveExpression(visitChildren(n)); + } + + @Override + public ModelElement visit(KeyProgramVariableSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyStatementSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyTypeSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyCcatchSV n, Void arg) { + return super.visit(n, arg); + } + + @Override + public ModelElement visit(KeyExecutionContextSV n, Void arg) { + return super.visit(n, arg); + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyTypeConverter.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyTypeConverter.java new file mode 100644 index 00000000000..7a0e7563541 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyTypeConverter.java @@ -0,0 +1,12 @@ +package de.uka.ilkd.key.java; + +/** + * @author Alexander Weigl + * @version 1 (05.03.22) + */ +public class JP2KeyTypeConverter { + private final Services services; + public JP2KeyTypeConverter(Services services) { + this.services=services; + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JPContext.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JPContext.java new file mode 100644 index 00000000000..e34703c555d --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JPContext.java @@ -0,0 +1,26 @@ +package de.uka.ilkd.key.java; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; + +/** + * @author Alexander Weigl + * @version 1 (05.03.22) + */ +public class JPContext { + private final ClassOrInterfaceDeclaration classContext; + private final CompilationUnit cu; + + public JPContext(CompilationUnit cu, ClassOrInterfaceDeclaration classContext) { + this.cu = cu; + this.classContext = classContext; + } + + public CompilationUnit getCompilationUnitContext() { + return cu; + } + + public ClassOrInterfaceDeclaration getClassDeclaration() { + return classContext; + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaParserFactory.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaParserFactory.java new file mode 100644 index 00000000000..7d4f527ed22 --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaParserFactory.java @@ -0,0 +1,27 @@ +package de.uka.ilkd.key.java; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.BlockStmt; + +import java.io.Reader; + +/** + * @author Alexander Weigl + * @version 1 (05.03.22) + */ +public class JavaParserFactory { + private final JavaService javaService; + + public JavaParserFactory(JavaService javaService) { + this.javaService = javaService; + } + + public ParseResult parseCompilationUnit(Reader reader) { + return javaService.createJavaParser().parse(reader); + } + + public ParseResult parseStatementBlock(String sr) { + return javaService.createJavaParser().parseBlock(sr); + } +} diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java index fee3643b139..68b4638a7a1 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JavaService.java @@ -1,24 +1,55 @@ package de.uka.ilkd.key.java; -import com.github.javaparser.JavaParser; -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.resolution.SymbolResolver; +import com.github.javaparser.Position; +import com.github.javaparser.*; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.comments.CommentsCollection; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.ast.visitor.VoidVisitor; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import com.github.javaparser.symbolsolver.JavaSymbolSolver; import com.github.javaparser.symbolsolver.model.resolution.TypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.ClassLoaderTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.*; +import de.uka.ilkd.key.java.abstraction.Type; +import de.uka.ilkd.key.java.declaration.FieldSpecification; +import de.uka.ilkd.key.java.declaration.VariableSpecification; +import de.uka.ilkd.key.java.transformations.KeyJavaPipeline; +import de.uka.ilkd.key.java.transformations.pipeline.ConstantStringExpressionEvaluator; +import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; +import de.uka.ilkd.key.logic.JavaBlock; +import de.uka.ilkd.key.logic.Namespace; +import de.uka.ilkd.key.logic.op.IProgramVariable; +import de.uka.ilkd.key.logic.op.ProgramVariable; +import de.uka.ilkd.key.proof.io.consistency.FileRepo; +import de.uka.ilkd.key.util.LinkedHashMap; +import de.uka.ilkd.key.util.*; +import de.uka.ilkd.key.util.parsing.BuildingExceptions; +import de.uka.ilkd.key.util.parsing.BuildingIssue; +import org.key_project.util.collection.ImmutableList; +import org.key_project.util.collection.ImmutableSLList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Facade for the JavaParser. @@ -33,18 +64,915 @@ public class JavaService { private static final Logger LOGGER = LoggerFactory.getLogger(JavaService.class); + /** + * the File object that describes the directory from which the internal + * classes are to be read. They are read in differently - therefore the + * second category. A null value indicates that the boot classes are to + * be read from an internal repository. + */ + private File bootClassPath; + + /** + * this mapping stores the relation between recoder and KeY entities in a + * bidirectional way. + *

+ * It is used for syntactical structures and types. + */ + private final KeyJPMapping mapping = new KeyJPMapping(); + + /** + * Counter used to enumerate the anonymous implicit classes used in parsing of Java Fragments + */ + private static AtomicInteger interactCounter = new AtomicInteger(); + + /** + * This flag indicates whether we are currently parsing library classes + * (special classes) + */ + private boolean parsingLibs = false; + + /** + * the object that handles the transformation from recoder AST to KeY AST + */ + private final JP2KeyConverter converter; + + /** + * the object that handles the transformation from recoder types to KeY + * types + */ + private final JP2KeyTypeConverter typeConverter; + + /** + * The list of dynamical created {@link CompilationUnit}s + * that contain the classes that are referenced but not defined. For those class types + * a dummy stub is created at parse time. + */ + private Collection dynamicallyCreatedCompilationUnits; + + + private final CompilationUnit compilationUnitOfVirtualClasses; + + private final Services services; + private final JavaParserFactory programFactory; + + + /** + * return the associated converter object + * + * @return not null + */ + public JP2KeyConverter getConverter() { + return converter; + } + + /** + * return the associated type converter object + * + * @return not null + */ + public JP2KeyTypeConverter getTypeConverter() { + return typeConverter; + } + + /** + * set this to true before parsing special classes and to false afterwards. + * + * @param v the state of the special parsing flage + */ + private void setParsingLibs(boolean v) { + parsingLibs = v; + } + + /** + * are we currently parsing library code (special classes)? + * + * @return true iff currently parsing special classes. + */ + public boolean isParsingLibs() { + return parsingLibs; + } + + public KeyJPMapping rec2key() { + return mapping; + } + + private void insertToMap(Node r, ModelElement k) { + if (r != null && k != null) { + rec2key().put(r, k); + } else { + LOGGER.debug("Rec2Key.insertToMap: Omitting entry (r = {} -> k = {})", r, k); + } + } + + //region parsing of compilation units + + /** + * parse a list of java files and transform it to the corresponding KeY + * entities. + *

+ * Each element of the array is treated as a filename to read in. + * + * @param cUnitStrings a list of strings, each element is interpreted as a file to be + * read. not null. + * @param fileRepo the fileRepo which will store the files + * @return a new list containing the recoder compilation units corresponding + * to the given files. + * @throws ParseExceptionInFile any exception occurring while treating the file is wrapped + * into a parse exception that contains the filename. + */ + + public List readCompilationUnitsAsFiles(List cUnitStrings, FileRepo fileRepo) + throws ParseExceptionInFile { + + List cUnits = recoderCompilationUnitsAsFiles(cUnitStrings, fileRepo); + var result = new ArrayList(cUnits.size()); + for (CompilationUnit cu : cUnits) { + try { + result.add(getConverter().processCompilationUnit(cu)); + } catch (Exception e) { + throw new ParseExceptionInFile("", e); //Find a better solution + } + } + return result; + } + + + /** + * parse a list of java files. + *

+ * Each element of the array is treated as a filename to read in. + * + * @param filenames a list of strings, each element is interpreted as a file to be + * read. not null. + * @param fileRepo the fileRepo which will store the files + * @return a new list containing the recoder compilation units corresponding + * to the given files. + */ + private List recoderCompilationUnitsAsFiles(List filenames, FileRepo fileRepo) + throws BuildingExceptions { + List cUnits = new ArrayList<>(); + parseSpecialClasses(fileRepo); + var result = filenames.stream().parallel().map(it -> parseCompilationUnit(it, fileRepo)) + .collect(Collectors.toList()); + + if (result.stream().anyMatch(it -> !it.isSuccessful())) { + var problems = result.stream().flatMap(it -> it.getProblems().stream()); + reportErrors(problems); + } + // transform program + transformModel(cUnits); + return result.stream().map(it -> it.getResult().get()).collect(Collectors.toList()); + } + + private void reportErrors(ParseResult result) { + if (!result.isSuccessful()) { + reportErrors(result.getProblems().stream()); + } + } + + private void reportErrors(List> result) { + if (result.stream().anyMatch(it -> !it.isSuccessful())) { + reportErrors(result.stream().flatMap(it -> it.getProblems().stream())); + } + } + + + private void reportErrors(Stream problems) { + var be = problems.map(it -> { + var loc = it.getLocation() + .flatMap(TokenRange::toRange) + .map(b -> b.begin) + .orElse(new Position(-1, -1)); + return new BuildingIssue(it.getVerboseMessage(), + null, false, loc.line, loc.column, -1, -1, null /*TODO*/); + }).collect(Collectors.toList()); + throw new BuildingExceptions(be); + } + + private ParseResult parseCompilationUnit(String filename, @Nullable FileRepo fileRepo) { + try { + Reader is; + if (fileRepo != null) + is = new InputStreamReader(fileRepo.getInputStream(Paths.get(filename))); + else + is = new FileReader(filename); + try (BufferedReader br = new BufferedReader(is)) { + ParseResult cu = getProgramFactory().parseCompilationUnit(br); + if (cu.getResult().isPresent()) { + cu.getResult().get().setStorage(Paths.get(filename)); + } + return cu; + } + + } catch (FileNotFoundException e) { + return new ParseResult<>(null, + Collections.singletonList(new Problem("Could not find " + filename, null, e)), new CommentsCollection()); + } catch (IOException e) { + return new ParseResult<>(null, + Collections.singletonList(new Problem("I/O error reading: " + filename, null, e)), new CommentsCollection()); + } + } + + /** + * read a compilation unit, given as a string. + * + * @param cUnitString a string represents a compilation unit + * @return a KeY structured compilation unit. + */ + public de.uka.ilkd.key.java.CompilationUnit readCompilationUnit(String cUnitString) { + var cc = recoderCompilationUnits(Collections.singletonList(cUnitString)); + var cu = cc.get(0); + return (de.uka.ilkd.key.java.CompilationUnit) getConverter().process(cu); + } + + /** + * read a number of compilation units, each given as a string. + * + * @param cUnitStrings an array of strings, each element represents a compilation + * unit + * @return a list of KeY structured compilation units. + */ + List recoderCompilationUnits(List cUnitStrings) { + parseSpecialClasses(); + var cUnits = cUnitStrings.parallelStream() + .map(it -> { + LOGGER.debug("Reading {}", trim(it)); + var sr = new StringReader(it); + return getProgramFactory().parseCompilationUnit(sr); + }).collect(Collectors.toList()); + + if (cUnits.stream().anyMatch(it -> !it.isSuccessful())) { + reportErrors(cUnits.stream().flatMap(it -> it.getProblems().stream())); + } + + // transform program + final var collect = cUnits.stream().map(it -> it.getResult().get()).collect(Collectors.toList()); + transformModel(collect); + return collect; + } + + // ----- parsing libraries + + public void setClassPath(File bootClassPath, List classPath) { + this.sourcePaths.clear(); + this.sourcePaths.addAll(classPath); + this.bootClassPath = bootClassPath; + typeSolver = null; + } + + /** + * get the list of names of classes that have been created dynamically due + * to lacking definitions. + *

+ * For all classes that are referenced but not defined, an empty dummy stub + * is created. This method returns the list of their fully qualified class + * names. + * + * @return an unmodifiable list of fully qualified class names + * @author mu, on rb's specification ;) + */ + public List getDynamicallyCreatedClasses() { + List ret = new ArrayList<>(); + if (dynamicallyCreatedCompilationUnits != null) { + for (CompilationUnit cu : dynamicallyCreatedCompilationUnits) { + final var pt = cu.getPrimaryTypeName(); + pt.ifPresent(ret::add); + } + } + return ret; + } + + /** + * This method loads the internal classes - also called the "boot" classes. + *

+ * If {@link #bootClassPath} is set to null, it locates java classes that + * are stored internally within the jar-file or the binary directory. The + * JAVALANG.TXT file lists all files to be loaded. The files are found using + * a special {@link JavaReduxFileCollection}. + *

+ * If, however, {@link #bootClassPath} is assigned a value, this is treated + * as a directory (not a JAR file at the moment) and all files in this + * directory are read in. This is done using a + * {@link DirectoryFileCollection}. + * + * @param fileRepo the FileRepo that provides the InputStream to resources + * @return + */ + private List parseInternalClasses(FileRepo fileRepo) throws IOException { + Stream paths; + + if (bootClassPath == null) { + var bootCollection = new JavaReduxFileCollection(services.getProfile()); + paths = bootCollection.getResources(); + } else { + paths = Files.walk(bootClassPath.toPath()) + .filter(it -> it.getFileName().endsWith(".java") || it.getFileName().endsWith(".jml")) + .map(it -> { + try { + return it.toUri().toURL(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return null; + }); + } + + var seq = paths.parallel().map(it -> { + try { + final var inputStream = fileRepo == null ? it.openStream() : fileRepo.getInputStream(it); + try (Reader f = new BufferedReader(new InputStreamReader(inputStream))) { + return getProgramFactory().parseCompilationUnit(f); + } + //Set storage location? + } catch (IOException e) { + e.printStackTrace(); + } + return null; + }).collect(Collectors.toList()); + + if (seq.stream().anyMatch(it -> !it.isSuccessful())) { + reportErrors(seq.stream().flatMap(it -> it.getProblems().stream())); + } + + return seq.stream().map(it -> it.getResult().get()).collect(Collectors.toList()); + } + + /** + * reads compilation units that will be treated as library classes. + *

+ * Proceed as follows: + * + *

    + *
  1. If "classPath" is set and contains at least one entry + *
      + *
    1. read every .java file within the entries (directories + * or zip files) + *
    2. read every .class file within the entries + * (directories or zip files) + *
    + *
  2. else read a special collection of classes that is stored internally + *
+ * + * @param fileRepo the FileRepo for obtaining InputStreams + * @throws IOException + * @author mulbrich + */ + private List parseLibs(FileRepo fileRepo) throws IOException { + + var internal = parseInternalClasses(fileRepo); + List sources = new ArrayList<>(); + List rcuList = new ArrayList<>(internal); + + for (var cp : sourcePaths) { + if (Files.isDirectory(cp)) { + sources.add(new DirectoryFileCollection(cp.toFile())); + } else { + sources.add(new ZipFileCollection(cp.toFile())); + } + } + + /* While the resources are read (and possibly copied) via the FileRepo, the data location + * is left as it is. This leaves the line information intact. */ + Path currentDataLocation; + + // -- read jml files -- + for (FileCollection fc : sources) { + FileCollection.Walker walker = fc.createWalker(".jml"); + while (walker.step()) { + currentDataLocation = walker.getCurrentLocation(); + try (InputStream is = walker.openCurrent(fileRepo); + Reader isr = new InputStreamReader(is); + Reader f = new BufferedReader(isr)) { + var rcu = getProgramFactory().parseCompilationUnit(f); + reportErrors(rcu); + var cu = rcu.getResult().get(); + cu.setStorage(currentDataLocation); + removeCodeFromClasses(cu, false); + rcuList.add(cu); + } + } + } + + // -- read java files -- + for (FileCollection fc : sources) { + FileCollection.Walker walker = fc.createWalker(".java"); + while (walker.step()) { + currentDataLocation = walker.getCurrentLocation(); + try (InputStream is = walker.openCurrent(fileRepo); + Reader isr = new InputStreamReader(is); + Reader f = new BufferedReader(isr)) { + var rcu = getProgramFactory().parseCompilationUnit(f); + reportErrors(rcu); + var cu = rcu.getResult().get(); + cu.setStorage(currentDataLocation); + removeCodeFromClasses(cu, true); + rcuList.add(cu); + } + } + } + + // -- read class files -- + /* + ClassFileDeclarationManager manager = new ClassFileDeclarationManager(pf); + ByteCodeParser parser = new ByteCodeParser(); + for (FileCollection fc : sources) { + FileCollection.Walker walker = fc.createWalker(".class"); + while (walker.step()) { + currentDataLocation = walker.getCurrentDataLocation(); + try (InputStream is = new BufferedInputStream(walker.openCurrent(fileRepo))) { + ClassFile cf = parser.parseClassFile(is); + manager.addClassFile(cf, currentDataLocation); + } catch (Exception ex) { + throw new ConvertException("Error while loading: " + walker.getCurrentDataLocation(), ex); + } + } + } + rcuList.addAll(manager.getCompilationUnits()); + */ + + var rcu = getProgramFactory().parseCompilationUnit( + new StringReader("public class " + JavaInfo.DEFAULT_EXECUTION_CONTEXT_CLASS + + " { public static void " + JavaInfo.DEFAULT_EXECUTION_CONTEXT_METHOD + "() {} }")); + reportErrors(rcu); + rcuList.add(rcu.getResult().get()); + return rcuList; + } + + /* + * removes code from a parsed compilation unit. This includes method bodies, + * initial assignments, compile-time constants, static blocks. + * + * This is done for classes that are read in a classpath-context. For these + * classes only contracts (if present) are to be considered. + * + * No need to inform changeHistory since the class is not yet registered. + * Method bodies are set to null, i.e. all methods are stubs only + * + * TODO remove jml-model methods (or similar) also? + * FIXME this does not work if jml set statements are last in a method + * TODO leave it out all together? + */ + private void removeCodeFromClasses(CompilationUnit rcu, boolean allowed) { + VoidVisitor removeBodies = new VoidVisitorAdapter<>() { + @Override + public void visit(MethodDeclaration n, Void arg) { + if (!allowed && n.getBody() != null) { + LOGGER.warn("Method body ({}) should not be allowed: {}", n.getNameAsString(), rcu.getStorage()); + } + n.setBody(null); + } + }; + rcu.accept(removeBodies, null); + } + + /** + * makes sure that the special classes (library classes) have been parsed + * in. + *

+ * If not parsed yet, the special classes are read in and converted. + * This method throws only runtime exceptions for historical reasons. + */ + public void parseSpecialClasses() { + parseLibraryClasses0(null); + } + + /** + * makes sure that the special classes (library classes) have been parsed + * in. + *

+ * If not parsed yet, the special classes are read in and converted. + * This method throws only runtime exceptions for historical reasons. + * + * @param fileRepo the fileRepo which will store the files + */ + public void parseSpecialClasses(FileRepo fileRepo) { + try { + parseLibraryClasses0(fileRepo); + } catch (Exception e) { + reportError("An error occurred while parsing the libraries", e); + } + } + + private void parseLibraryClasses0(FileRepo fileRepo) { + if (mapping.parsedSpecial()) { + return; + } + // go to special mode -> used by the converter! + setParsingLibs(true); + + try { + List specialClasses = parseLibs(fileRepo); + /* + dynamicallyCreatedCompilationUnits = keySourceInfo.getCreatedStubClasses(); + specialClasses.addAll(dynamicallyCreatedCompilationUnits); + keySourceInfo.setIgnoreUnresolvedClasses(false); + changeHistory.updateModel(); + */ + transformModel(specialClasses); + + // make them available to the rec2key mapping + for (CompilationUnit cu : specialClasses) { + var dl = cu.getStorage(); + if (dl.isEmpty()) throw new AssertionError("DataLocation not set on compilation unit"); + getConverter().processCompilationUnit(cu); + } + + /* TODO weigl + // Ensure that rec2key is complete (at least the NullType needs to be available!) + if (!rec2key().mapped(getNameInfo().getNullType())) { + Sort objectSort = services.getNamespaces().sorts().lookup(new Name("java.lang.Object")); + assert objectSort != null; + NullSort nullSort = new NullSort(objectSort); + KeYJavaType result = new KeYJavaType(NullType.JAVA_NULL, nullSort); + if (services.getNamespaces().sorts().lookup(nullSort.name()) == null) { + services.getNamespaces().sorts().add(nullSort); + } + rec2key().put(servConf.getNameInfo().getNullType(), result); + } + */ + + } catch (IOException e) { + e.printStackTrace(); + } + + // tell the mapping that we have parsed the special classes + rec2key().parsedSpecial(true); + + setParsingLibs(false); + } + + /** + * Transform a list of compilation units. + *

+ * Once a compilation unit has been parsed in and prior to converting it to + * the KeY structures, several transformations have to be performed upon it. + *

+ * You can add your own Transformation here. Make sure it is in the correct + * order. + * + * @param cUnits a list of compilation units, not null. + */ + + protected void transformModel(List cUnits) { + KeyJavaPipeline pipeline = KeyJavaPipeline.createDefault(createPipelineServices(cUnits)); + pipeline.apply(); + } + + + // ----- methods dealing with blocks. + + /** + * wraps a RECODER StatementBlock in a method + *

+ * it is wrapped in a method called + * <virtual_method_for_parsing>. + * + * @param block the StatementBlock to wrap + * @return the enclosing MethodDeclaration + */ + protected MethodDeclaration embedBlock(BlockStmt block) { + MethodDeclaration mdecl = new MethodDeclaration(new NodeList<>(), new VoidType(), + "$virtual_method_for_parsing"); + mdecl.setBody(block); + return mdecl; + } + + /** + * wraps a RECODER MethodDeclaration in a class + * + * @param mdecl the declaration.MethodDeclaration to wrap + * @param context the declaration.ClassDeclaration where the method + * has to be embedded + * @return the enclosing declaration.ClassDeclaration + */ + protected ClassOrInterfaceDeclaration embedMethod(MethodDeclaration mdecl, JPContext context) { + ClassOrInterfaceDeclaration classContext = context.getClassDeclaration(); + classContext.addMember(mdecl); + /*for (int i = 0, sz = memberList.size(); i < sz; i++) { + if (memberList.get(i) instanceof MethodDeclaration) { + MethodDeclaration olddecl = + (MethodDeclaration) memberList.get(i); + if (olddecl.getName().equals(mdecl.getName())) { + memberList.remove(i); + } + } + }*/ + return classContext; + } + + /** + * creates an empty RECODER compilation unit with a temporary name. + * + * @return the new CompilationUnit + */ + public JPContext createEmptyContext() { + var classContext = interactClassDecl(); + var cu = new CompilationUnit(null, new NodeList<>(), new NodeList<>(classContext), null); + getSymbolResolver().inject(cu); + return new JPContext(cu, classContext); + } + + /** + * create a new Context with a temporary name and make a list of variables + * visible from within. + * + * @param vars a list of variables + * @param csi a special source info + * @return a newly created context. + */ + protected JPContext createContext(ImmutableList vars) { + var classContext = interactClassDecl(); + addProgramVariablesToClassContext(classContext, vars); + var cu = new CompilationUnit(null, new NodeList<>(), new NodeList<>(classContext), null); + getSymbolResolver().inject(cu); + return new JPContext(cu, classContext); + } + + /** + * add a list of variables to a context + * + * @param classContext context to add to + * @param vars vars to add + */ + private void addProgramVariablesToClassContext(ClassOrInterfaceDeclaration classContext, + ImmutableList vars) { + Map names2var = new LinkedHashMap<>(); + Set names = new HashSet<>(); + + for (ProgramVariable var : vars) { + if (names.contains(var.name().toString())) { + continue; + } + VariableSpecification keyVarSpec = lookupVarSpec(var); + names.add(var.name().toString()); + if (keyVarSpec == null) { + keyVarSpec = new FieldSpecification(var); + } + + if (var.getKeYJavaType() == null) { + /// The program variable "variant" introduced to prove loop termination has sort + /// "any" and, hence, no type. Parsing modalities fails on branches on which the + /// variable exists. Therefore, it seems better to silently ignore such program + /// variables (not making themaccessible) rather than to throw an exception. + /// MU 01.2019 + // throw new IllegalArgumentException("Variable " + var + " has no type"); + continue; + } + + Type javaType = var.getKeYJavaType().getJavaType(); + if (javaType == null) continue; + String typeName = javaType.getFullName(); + + + FieldDeclaration recVar = new FieldDeclaration(new NodeList<>(), + new VariableDeclarator(name2typeReference(typeName), keyVarSpec.getName())); + + classContext.addMember(recVar); + var rvarspec = recVar.getVariables().get(0); + names2var.put(var.name().toString(), rvarspec); + insertToMap(recVar.getVariables().get(0), keyVarSpec); + } + } + + /** + * look up in the mapping the variable specification for a program variable. + *

+ * used by addProgramVariablesToClassContext + */ + private VariableSpecification lookupVarSpec(ProgramVariable pv) { + for (final Object o : mapping.elemsKeY()) { + if ((o instanceof VariableSpecification) && ((VariableSpecification) o).getProgramVariable() == pv) { + return (VariableSpecification) o; + } + } + return null; + } + + /** + * given a name as string, construct a recoder type reference from it. + * + * @param typeName non-null type name as string + * @return a freshly created type reference to the given type. + */ + private com.github.javaparser.ast.type.Type name2typeReference(String typeName) { + return new ClassOrInterfaceType(null, typeName); + + /*PackageReference pr = null; + String baseType = TypeNameTranslator.getBaseType(typeName); + int idx = baseType.indexOf('.'); + int lastIndex = 0; + String anonType = ""; + while (idx != -1 && baseType.charAt(lastIndex) >= 'a' + && baseType.charAt(lastIndex) <= 'z') { + String s = baseType.substring(lastIndex, idx); + pr = new PackageReference(pr, new Identifier(s)); + lastIndex = idx + 1; + idx = baseType.indexOf('.', lastIndex); + } + baseType = anonType + baseType; + Identifier typeId; + if (baseType.charAt(0) == '<') { + typeId = new ImplicitIdentifier(baseType.substring(lastIndex)); + } else { + typeId = new ObjectTypeIdentifier(baseType.substring(lastIndex)); + } + TypeReference result = new TypeReference(pr, typeId); + result.setDimensions(TypeNameTranslator.getDimensions(typeName)); + return result; + */ + } + + /** + * parses a given JavaBlock using the context to determine the right + * references and returns a statement block of recoder. + * + * @param block a String describing a java block + * @param context CompilationUnit in which the block has to be + * interpreted + * @return the parsed and resolved recoder statement block + */ + BlockStmt recoderBlock(String block, JPContext context) { + parseSpecialClasses(); + var bl = getProgramFactory().parseStatementBlock(block); + if (!bl.isSuccessful()) { + reportErrors(bl); + } + final var blockStmt = bl.getResult().get(); + embedMethod(embedBlock(blockStmt), context); + // normalise constant string expressions + List cunits = new ArrayList<>(); + cunits.add(context.getCompilationUnitContext()); + new ConstantStringExpressionEvaluator(createPipelineServices()).apply(context.getClassDeclaration()); + return blockStmt; + } + + private TransformationPipelineServices createPipelineServices() { + return createPipelineServices(new ArrayList<>(0)); + } + + private TransformationPipelineServices createPipelineServices(List cUnits) { + TransformationPipelineServices.TransformerCache cache = new TransformationPipelineServices.TransformerCache(cUnits); + return new TransformationPipelineServices(this, cache); + } + + + /** + * parses a given JavaBlock using the context to determine the right + * references + * + * @param block a String describing a java block + * @param context CompilationUnit in which the block has to be + * interprested + * @return the parsed and resolved JavaBlock + */ + public JavaBlock readBlock(String block, JPContext context) { + var sb = recoderBlock(block, context); + return JavaBlock.createJavaBlock((StatementBlock) getConverter().process(sb)); + } + + /** + * parses a given JavaBlock using the context to determine the right + * references using an empty context + * + * @param block a String describing a java block + * @return the parsed and resolved JavaBlock + */ + public JavaBlock readBlockWithEmptyContext(String block) { + return readBlock(block, createEmptyContext()); + } + + /** + * parses a given JavaBlock using a namespace to determine the right + * references using an empty context. The variables of the namespace are + * used to create a new class context + * + * @param s a String describing a java block + * @return the parsed and resolved JavaBlock + */ + public JavaBlock readBlockWithProgramVariables(Namespace variables, String s) { + ImmutableList pvs = ImmutableSLList.nil(); + for (IProgramVariable n : variables.allElements()) { + if (n instanceof ProgramVariable) { + pvs = pvs.append((ProgramVariable) n); //preserve the order (nested namespaces!) + } + } + return readBlock(s, createContext(pvs)); + } + + /** + * make a new classdeclaration with a temporary name. + *

+ * The name is a unique implicit identifier. + * + * @return a newly created recoder ClassDeclaration with a unique name + */ + private ClassOrInterfaceDeclaration interactClassDecl() { + var classContext = new ClassOrInterfaceDeclaration(new NodeList<>(), false, + "$virtual_class_for_parsing" + interactCounter.incrementAndGet()); + return classContext; + } + + // ----- helpers + + /** + * reduce the size of a string to a maximum of 150 characters. Introduces + * ellipses [...] + */ + private static String trim(String s) { + return trim(s, 150); + } + + /** + * reduce the size of a string to a maximum of length. + */ + private static String trim(String s, int length) { + if (s.length() > length) + return s.substring(0, length - 5) + "[...]"; + return s; + } + + // ----- error handling + + /** + * tries to parse recoders exception position information + */ + private static int[] extractPositionInfo(String errorMessage) { + if (errorMessage == null || errorMessage.indexOf('@') == -1) { + return new int[0]; + } + int line = -1; + int column = -1; + try { + String pos = errorMessage.substring(errorMessage.indexOf("@") + 1); + pos = pos.substring(0, pos.indexOf(" ")); + line = Integer.parseInt(pos.substring(0, pos.indexOf('/'))); + column = Integer.parseInt(pos.substring(pos.indexOf('/') + 1)); + } catch (NumberFormatException nfe) { + LOGGER.debug("recoder2key:unresolved reference at " + "line:" + line + " column:" + column); + return new int[0]; + } catch (StringIndexOutOfBoundsException siexc) { + return new int[0]; + } + return new int[]{line, column}; + } + + /** + * report an error in form of a ConvertException. The cause is always + * attached to the resulting exception. + * + * @param message message to be used. + * @param t the cause of the exceptional case + * @throws ConvertException always + */ + public static void reportError(String message, Throwable t) { + // Attention: this highly depends on Recoders exception messages! + Throwable cause = t; + if (t instanceof ExceptionHandlerException && t.getCause() != null) { + cause = t.getCause(); + } + + if (cause instanceof PosConvertException) { + throw (PosConvertException) cause; + } + + int[] pos = extractPositionInfo(cause.toString()); + final RuntimeException rte; + if (pos.length > 0) { + rte = new PosConvertException(message, pos[0], pos[1]); + rte.initCause(cause); + } else { + rte = new ConvertException(message, cause); + } + + throw rte; + } + + + /** + * A list of {@link File} objects that describes the classpath to be searched + * for classes or Java files. + */ @Nonnull - private final List sourcePaths; + private final List sourcePaths; + @Nullable private ParserConfiguration config; + @Nullable private TypeSolver typeSolver; @Nullable - private SymbolResolver symbolResolver; + private JavaSymbolSolver symbolResolver; + + private boolean useSystemClassLoaderInResolution; - public JavaService(Collection sourcePaths) { + public JavaService(Services services, Collection sourcePaths) { + this.services = services; this.sourcePaths = new ArrayList<>(sourcePaths); + converter = new JP2KeyConverter(services, mapping); + typeConverter = new JP2KeyTypeConverter(services); + programFactory = new JavaParserFactory(this); + compilationUnitOfVirtualClasses = null; } public JavaParser createJavaParser() { @@ -61,7 +989,7 @@ private ParserConfiguration getConfiguration() { } @Nonnull - private SymbolResolver getSymbolResolver() { + private JavaSymbolSolver getSymbolResolver() { if (symbolResolver == null) { symbolResolver = new JavaSymbolSolver(getTypeSolver()); } @@ -72,20 +1000,50 @@ private SymbolResolver getSymbolResolver() { public TypeSolver getTypeSolver() { if (typeSolver == null) { var ct = new CombinedTypeSolver(); - for (File sourcePath : sourcePaths) { - if (sourcePath.isFile() && sourcePath.getName().endsWith(".jar")) { - try { - ct.add(new JarTypeSolver(sourcePath)); - } catch (IOException e) { - LOGGER.error(e.getMessage(), e); + for (var sourcePath : sourcePaths) { + if (Files.isRegularFile(sourcePath)) { + if (sourcePath.getFileName().endsWith(".jar")) { + try { + ct.add(new JarTypeSolver(sourcePath)); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } + } else { + /*sourcePath.getRoot(); + final Matcher matcher = IOUtil.URL_JAR_FILE.matcher(); + if (matcher.matches()) { + */ + //TODO add support for java files inside } - } else if (sourcePath.isDirectory()) { + } else if (Files.isDirectory(sourcePath)) { ct.add(new JavaParserTypeSolver(sourcePath, config)); } } - ct.add(new ClassLoaderTypeSolver(ClassLoader.getSystemClassLoader())); + + if (useSystemClassLoaderInResolution) { + ct.add(new ReflectionTypeSolver(true)); + } + typeSolver = ct; } return typeSolver; } -} + + /** + * If set to true the symbol solver do not use the {@link ClassLoaderTypeSolver} with the system class class loader. + * This means, that classes defined by the JRE are not found, if they are not given in the class path. + * In particular, only JavaRedux and Red classes (if added) are + *

+ * the next parser runs + * + * @param useSystemClassLoaderInResolution + */ + public void setUseSystemClassLoaderInResolution(boolean useSystemClassLoaderInResolution) { + this.useSystemClassLoaderInResolution = useSystemClassLoaderInResolution; + typeSolver = null; + } + + public JavaParserFactory getProgramFactory() { + return programFactory; + } +} \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/KeyJPMapping.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/KeyJPMapping.java new file mode 100644 index 00000000000..118d0eee6ff --- /dev/null +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/KeyJPMapping.java @@ -0,0 +1,170 @@ +package de.uka.ilkd.key.java; + +import com.github.javaparser.ast.Node; +import de.uka.ilkd.key.java.abstraction.KeYJavaType; +import de.uka.ilkd.key.util.Debug; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * @author Alexander Weigl + * @version 1 (05.03.22) + */ +public class KeyJPMapping { + public static final Logger LOGGER = LoggerFactory.getLogger(KeyJPMapping.class); + + /** + * have special classes been parsed in + */ + private boolean parsedSpecial = false; + + /** + * maps a recoder programelement (or something similar, e.g. Type) + * to the KeY-equivalent + */ + private final HashMap map; + + /** + * maps a KeY programelement to the Recoder-equivalent + */ + private final Map revMap; + + /** + * a pseudo super class for all arrays used to declare length + */ + private KeYJavaType superArrayType = null; + + + public KeyJPMapping() { + this.map = new LinkedHashMap<>(4096); + this.revMap = new LinkedHashMap<>(4096); + } + + + /** + * creates a KeYRecoderMapping object. + * Used for cloning and testing. + * + * @param map a HashMap mapping ProgramElements in Recoder to + * ProgramElements in KeY + * @param revMap the reverse map (KeY->Recoder) + * @param parsedSpecial boolean indicating if the special classes have been parsed in + */ + KeyJPMapping(HashMap map, Map revMap, + KeYJavaType superArrayType, + boolean parsedSpecial) { + this.map = map; + this.revMap = revMap; + this.superArrayType = superArrayType; + this.parsedSpecial = parsedSpecial; + } + + /** + * returns a matching ModelElement (KeY) to a given recoder.ModelElement + * + * @param pe a recoder.ModelElement + */ + public ModelElement toKeY(Node pe) { + return map.get(pe); + } + + + /** + * returns the Recoder-equivalent to a given ProgramElement (KeY). + * If there's no RecodeR equivalent to program element pe, an + * assertion failure "Program Element not known" is emitted. + * + * @param pe a JavaProgramElement + */ + public Node toRecoder(ProgramElement pe) { + Node res = revMap.get(pe); + Debug.assertTrue(res != null, "Program Element not known", pe); + return res; + } + + + /** + * returns the Recoder-equivalent to a given ModelElement (KeY). + * If there's no Recoder-equivalent to the ModelElement pe a + * debug message "Model Element not known" is printed. + * + * @param pe a ModelElement + */ + public Node toRecoder(ModelElement pe) { + Node res = revMap.get(pe); + Debug.assertTrue(res != null, "Model Element not known", pe); + + return res; + } + + public void put(Node rec, ModelElement key) { + Object formerValue = map.put(rec, key); + Debug.assertTrue(formerValue == null, + "keyrecodermapping: duplicate registration of type:", key); + revMap.put(key, rec); + LOGGER.warn("Size of rec2key: {} entries", map.size()); + } + + public boolean mapped(Object rec) { + return map.containsKey(rec); + } + + + public Set elemsKeY() { + LOGGER.error("Size of rec2key: {} entries", map.size()); + return revMap.keySet(); + } + + public Set elemsRec() { + return map.keySet(); + } + + public void setSuperArrayType(KeYJavaType superArrayType) { + this.superArrayType = superArrayType; + } + + public KeYJavaType getSuperArrayType() { + return this.superArrayType; + } + + public KeyJPMapping copy() { + return new KeyJPMapping(new HashMap<>(map), new HashMap<>(revMap), superArrayType, parsedSpecial); + } + + /** + * As long as we do not support lemmata we need the source code of + * some 'java.lang' classes. These are parsed in using method + * parseSpecial of {@link Recoder2KeY}. To avoid multiple readings + * this method indicates whether the special have been parsed in or + * not. + * + * @return true if special classes have been parsed in + */ + public boolean parsedSpecial() { + return parsedSpecial; + } + + public int size() { + return map.size(); + } + + + /** + * As long as we do not support lemmata we need the source code of + * some 'java.lang' classes. These are parsed in using method + * parseSpecial of {@link Recoder2KeY}. To avoid multiple readings + * this method sets a flag whether the special have been parsed in or + * not + * + * @param b boolean indicating if the special classes have been + * parsed in + */ + public void parsedSpecial(boolean b) { + parsedSpecial = b; + } +} diff --git a/key/key.java/src/test/java/KeyJavaPipelineTest.java b/key/key.java/src/test/java/KeyJavaPipelineTest.java index 8f66cd03d6b..c4f6ccde77e 100644 --- a/key/key.java/src/test/java/KeyJavaPipelineTest.java +++ b/key/key.java/src/test/java/KeyJavaPipelineTest.java @@ -1,3 +1,4 @@ +import com.github.javaparser.ParseResult; import com.github.javaparser.Problem; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.TypeDeclaration; @@ -9,21 +10,25 @@ import com.github.javaparser.printer.configuration.PrinterConfiguration; import com.google.common.truth.Truth; import de.uka.ilkd.key.java.JavaService; +import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.transformations.KeyJavaPipeline; import de.uka.ilkd.key.java.transformations.pipeline.JavaTransformer; import de.uka.ilkd.key.java.transformations.pipeline.TransformationPipelineServices; +import de.uka.ilkd.key.proof.init.JavaProfile; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import java.util.stream.Stream; /** @@ -31,46 +36,51 @@ * @version 1 (19.02.22) */ class KeyJavaPipelineTest { - public KeyJavaPipeline createPipelineTest(File testFolder) throws FileNotFoundException { - var js = new JavaService(Collections.singleton(testFolder)); - var inputFolder = new File(testFolder, "input"); + public KeyJavaPipeline createPipelineTest(Path testFolder) throws IOException { + Services services = new Services(JavaProfile.getDefaultProfile()); + var js = new JavaService(services, Collections.singleton(testFolder)); + var inputFolder = testFolder.resolve("input"); final var jp = js.createJavaParser(); - var files = inputFolder.listFiles(); + var files = Files.list(inputFolder); var cu = new ArrayList(); - for (File it : Objects.requireNonNull(files)) { - var r = jp.parse(it); - if (!r.isSuccessful()) { - for (Problem problem : r.getProblems()) { - System.out.println(problem); + files.forEach(it -> { + try { + ParseResult r = jp.parse(it); + if (!r.isSuccessful()) { + for (Problem problem : r.getProblems()) { + System.out.println(problem); + } + throw new IllegalStateException(); } - throw new IllegalStateException(); + var c = r.getResult().get(); + cu.add(c); + } catch (IOException e) { + throw new RuntimeException(e); } - var c = r.getResult().get(); - cu.add(c); - } - var services = new TransformationPipelineServices(js, new TransformationPipelineServices.TransformerCache(cu)); - var kjp = KeyJavaPipeline.createDefault(services); - var kjp2 = new KeyJavaPipeline(services); + }); + var tservices = new TransformationPipelineServices(js, new TransformationPipelineServices.TransformerCache(cu)); + var kjp = KeyJavaPipeline.createDefault(tservices); + var kjp2 = new KeyJavaPipeline(tservices); var cnt = 0; for (JavaTransformer step : kjp.getSteps()) { kjp2.add(step); - final var file = new File(new File(testFolder, "actual"), + final var file = testFolder.resolve("actual").resolve( String.format("%02d_%s", ++cnt, step.getClass().getSimpleName())); - kjp2.add(new DebugOutputTransformer(file, services)); + kjp2.add(new DebugOutputTransformer(file, tservices)); } return kjp2; } @TestFactory Stream simple() throws IOException { - return generatePipelineTests(new File("pipelineTests/simple").getAbsoluteFile()); + return generatePipelineTests(Paths.get("pipelineTests/simple").toAbsolutePath()); } - private Stream generatePipelineTests(File testFolder) throws IOException { + private Stream generatePipelineTests(Path testFolder) throws IOException { var pt = createPipelineTest(testFolder); pt.apply(); - var expected = new File(testFolder, "expected").toPath(); - var actual = new File(testFolder, "actual").toPath(); + var expected = testFolder.resolve("expected"); + var actual = testFolder.resolve("actual"); return Files.walk(expected) .filter(Files::isRegularFile) @@ -90,30 +100,34 @@ private void checkEqualFile(Path expectedFile, Path expectedFolder, Path actualF } private static class DebugOutputTransformer extends JavaTransformer { - final File outputFolder; - final Set alreadyWritten = new HashSet<>(); + final Path outputFolder; + final Set alreadyWritten = new HashSet<>(); private static final Logger LOGGER = LoggerFactory.getLogger(DebugOutputTransformer.class); private final Printer myPrinter = new DefaultPrettyPrinter( MyPrintVisitor::new, new DefaultPrinterConfiguration()); - public DebugOutputTransformer(File s, TransformationPipelineServices services) { + public DebugOutputTransformer(Path s, TransformationPipelineServices services) { super(services); outputFolder = s; } @Override public void apply(TypeDeclaration td) { - outputFolder.mkdirs(); + try { + Files.createDirectories(outputFolder); + } catch (IOException e) { + e.printStackTrace(); + } for (CompilationUnit unit : services.getCache().getUnits()) { var name = unit.getPrimaryTypeName().get(); - var file = new File(outputFolder, name + ".java"); + var file = outputFolder.resolve(name + ".java"); if (!alreadyWritten.contains(file)) { alreadyWritten.add(file); try { unit.printer(myPrinter); - Files.writeString(file.toPath(), unit.toString()); + Files.writeString(file, unit.toString()); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java index eef7a5a8922..606649ca905 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Log.java @@ -1,6 +1,5 @@ package de.uka.ilkd.key.core; -import ch.qos.logback.classic.Level; import ch.qos.logback.classic.filter.ThresholdFilter; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; @@ -13,6 +12,9 @@ * @version 1 (7/19/21) */ public class Log { + + private Log() {} + /** * Global log for simple reason. */ @@ -25,31 +27,13 @@ public class Log { public static final Logger LDEVEL = LoggerFactory.getLogger("key.devel"); - public static void configureLogging(int verbosity) { + public static void configureLogging(Verbosity verbosity) { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); Appender consoleAppender = root.getAppender("STDOUT"); var filter = new ThresholdFilter(); consoleAppender.addFilter(filter); - switch (verbosity) { - case Verbosity.TRACE: - filter.setLevel("TRACE"); - break; - case Verbosity.DEBUG: - filter.setLevel("DEBUG"); - break; - case Verbosity.INFO: - filter.setLevel("INFO"); - break; - case Verbosity.NORMAL: - filter.setLevel("ERROR"); - break; - case Verbosity.SILENT: - filter.setLevel("OFF"); - break; - default: - filter.setLevel("WARN"); - break; - } + filter.setLevel("WARN"); + filter.setLevel(verbosity.name()); } } diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java index a5ffbe6e8ef..e50b60c94fd 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/core/Main.java @@ -23,6 +23,7 @@ import de.uka.ilkd.key.macros.ProofMacro; import de.uka.ilkd.key.macros.SkipMacro; import de.uka.ilkd.key.proof.init.AbstractProfile; +import de.uka.ilkd.key.proof.init.ProofInputException; import de.uka.ilkd.key.proof.io.AutoSaver; import de.uka.ilkd.key.proof.io.RuleSourceFactory; import de.uka.ilkd.key.settings.GeneralSettings; @@ -44,8 +45,8 @@ import org.xml.sax.SAXException; import recoder.ParserException; +import javax.annotation.Nonnull; import javax.xml.parsers.ParserConfigurationException; -import java.awt.*; import java.io.File; import java.io.IOException; import java.io.PrintStream; @@ -53,6 +54,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Objects; /** * The main entry point for KeY @@ -91,8 +93,6 @@ public final class Main { private static final String RIFL = "--rifl"; public static final String JKEY_PREFIX = "--jr-"; public static final String JMAX_RULES = JKEY_PREFIX + "maxRules"; - // deprecated -// public static final String JPATH_OF_RULE_FILE = JKEY_PREFIX + "pathOfRuleFile"; public static final String JPATH_OF_RESULT = JKEY_PREFIX + "pathOfResult"; public static final String JTIMEOUT = JKEY_PREFIX + "timeout"; public static final String JPRINT = JKEY_PREFIX + "print"; @@ -125,7 +125,7 @@ private enum UiMode { /** * Level of verbosity for command line outputs. */ - private static byte verbosity = Verbosity.NORMAL; + private static Verbosity verbosity = Verbosity.NORMAL; private static String examplesDir = null; @@ -236,7 +236,7 @@ private static void logInformation() { LOGGER.debug("Hardware: {}", System.getProperty("java.hw")); Runtime rt = Runtime.getRuntime(); LOGGER.debug("Total memory: {} MB", (rt.totalMemory() / 1048576.0)); - LOGGER.debug("Maximum memory: {} MB" , (rt.maxMemory() / 1048576.0)); + LOGGER.debug("Maximum memory: {} MB", (rt.maxMemory() / 1048576.0)); LOGGER.debug("Free memory: {} MB", (rt.freeMemory() / 1048576.0)); LOGGER.debug("Available processors: {}", rt.availableProcessors()); } @@ -273,7 +273,8 @@ private static CommandLine createCommandLine() { cl.addTextPart("--K-help", "display help for technical/debug parameters\n", true); cl.addOption(SHOW_PROPERTIES, null, "list all Java properties and exit"); cl.addOption(LAST, null, "start prover with last loaded problem (only possible with GUI)"); - cl.addOption(AUTOSAVE, "", "save intermediate proof states each n proof steps to a temporary location (default: 0 = off)"); + cl.addOption(AUTOSAVE, "", "save intermediate proof states each n proof steps " + + "to a temporary location (default: 0 = off)"); cl.addOption(EXPERIMENTAL, null, "switch experimental features on"); cl.addOption(NO_PRUNING_CLOSED, null, "disables pruning and goal back in closed branches (saves memory)"); @@ -290,18 +291,25 @@ private static CommandLine createCommandLine() { cl.addOption(RIFL, "", "load RIFL specifications from file (requires GUI and startup file)"); cl.addOption(MACRO, "", "apply automatic proof macro"); cl.addOption(SAVE_ALL_CONTRACTS, null, "save all selected contracts for automatic execution"); - cl.addOption(TIMEOUT, "", "timeout for each automatic proof of a problem in ms (default: " + LemmataAutoModeOptions.DEFAULT_TIMEOUT + ", i.e., no timeout)"); + cl.addOption(TIMEOUT, "", "timeout for each automatic proof of a problem in ms " + + "(default: " + LemmataAutoModeOptions.DEFAULT_TIMEOUT + ", i.e., no timeout)"); cl.addSection("Options for justify rules:"); - cl.addOption(JUSTIFY_RULES, "", "autoprove taclets (options always with prefix --jr) needs the path to the rule file as argument"); + cl.addOption(JUSTIFY_RULES, "", "autoprove taclets " + + "(options always with prefix --jr) needs the path to the rule file as argument"); cl.addText("\n", true); - cl.addText("The '" + JUSTIFY_RULES + "' option has a number of additional parameters you can set.", false); - cl.addText("The following options only apply if '" + JUSTIFY_RULES + "' is used.", false); + cl.addText("The '" + JUSTIFY_RULES + "' option has a number of additional parameters you can set.", + false); + cl.addText("The following options only apply if '" + JUSTIFY_RULES + "' is used.", + false); cl.addText("\n", true); - cl.addOption(JMAX_RULES, "", "maximum number of rule application to perform (default: " + LemmataAutoModeOptions.DEFAULT_MAXRULES + ")"); + cl.addOption(JMAX_RULES, "", "maximum number of rule application to perform " + + "(default: " + LemmataAutoModeOptions.DEFAULT_MAXRULES + ")"); cl.addOption(JPATH_OF_RESULT, "", "store proofs to this folder"); - cl.addOption(JTIMEOUT, "", "the timeout for proof of a taclet in ms (default: " + LemmataAutoModeOptions.DEFAULT_TIMEOUT + ")"); + cl.addOption(JTIMEOUT, "", "the timeout for proof of a taclet in ms " + + "(default: " + LemmataAutoModeOptions.DEFAULT_TIMEOUT + ")"); cl.addOption(JPRINT, "", "send output to terminal or disable output"); - cl.addOption(JSAVE_RESULTS_TO_FILE, "", "save or drop proofs (then stored to path given by " + JPATH_OF_RESULT + ")"); + cl.addOption(JSAVE_RESULTS_TO_FILE, "", "save or drop proofs " + + "(then stored to path given by " + JPATH_OF_RESULT + ")"); cl.addOption(JFILE_FOR_AXIOMS, "", "read axioms from given file"); cl.addOption(JFILE_FOR_DEFINITION, "", "read definitions from given file"); return cl; @@ -314,9 +322,7 @@ private static CommandLine createCommandLine() { */ public static void evaluateOptions(CommandLine cl) { if (cl.isSet(EXPERIMENTAL)) { - if (verbosity > Verbosity.SILENT) { - LOGGER.info("Running in experimental mode ..."); - } + LOGGER.info("Running in experimental mode ..."); setEnabledExperimentalFeatures(true); } else { setEnabledExperimentalFeatures(false); @@ -325,7 +331,8 @@ public static void evaluateOptions(CommandLine cl) { if (cl.isSet(VERBOSITY)) { // verbosity try { - verbosity = (byte) cl.getInteger(VERBOSITY, Verbosity.DEBUG); + var v = cl.getInteger(VERBOSITY, Verbosity.DEBUG.ordinal()); + verbosity = Verbosity.values()[v]; } catch (CommandLineException e) { if (Debug.ENABLE_DEBUG) { e.printStackTrace(); @@ -334,19 +341,14 @@ public static void evaluateOptions(CommandLine cl) { } } - if (verbosity > Verbosity.SILENT) { - printHeader(); - } + printHeader(); if (cl.isSet(SHOW_PROPERTIES)) { - try { - java.util.Properties props = System.getProperties(); - for (Object o : props.keySet()) { - LOGGER.info("" + o + "=\"" + props.get(o) + "\""); - } - } finally { - System.exit(0); + java.util.Properties props = System.getProperties(); + for (var o : props.entrySet()) { + LOGGER.info("{} = {}", o.getKey(), o.getValue()); } + System.exit(0); } if (cl.isSet(AUTO)) { @@ -383,20 +385,13 @@ public static void evaluateOptions(CommandLine cl) { } if (cl.isSet(TIMEOUT)) { - if (verbosity >= Verbosity.DEBUG) { - LOGGER.info("Timeout is set"); - } + LOGGER.info("Timeout is set"); long timeout = -1; try { timeout = cl.getLong(TIMEOUT, -1); - if (verbosity >= Verbosity.DEBUG) { - LOGGER.info("Timeout is: " + timeout + " ms"); - } + LOGGER.info("Timeout is: {} ms", timeout); } catch (CommandLineException e) { - if (Debug.ENABLE_DEBUG) { - e.printStackTrace(); - } - LOGGER.warn(e.getMessage()); + LOGGER.error("Could not parse the command line option {}", TIMEOUT, e); } if (timeout < -1) { @@ -410,32 +405,14 @@ public static void evaluateOptions(CommandLine cl) { examplesDir = cl.getString(EXAMPLES, null); } - if (verbosity > Verbosity.SILENT) { - if (Debug.ENABLE_DEBUG) { - LOGGER.info("Running in debug mode"); - } + LOGGER.info("DEBUG mode is {}", Debug.ENABLE_DEBUG ? "on" : "off"); + LOGGER.info("Assertions are {}", Debug.ENABLE_ASSERTION ? "on" : "off"); - if (Debug.ENABLE_ASSERTION) { - LOGGER.info("Using assertions"); - } else { - LOGGER.info("Not using assertions"); - } - } - - if (cl.isSet(EXPERIMENTAL)) { - if (verbosity > Verbosity.SILENT) { - LOGGER.info("Running in experimental mode ..."); - } - setEnabledExperimentalFeatures(true); - } else { - setEnabledExperimentalFeatures(false); - } + setEnabledExperimentalFeatures(cl.isSet(EXPERIMENTAL)); if (cl.isSet(RIFL)) { riflFileName = new File(cl.getString(RIFL, null)); - if (verbosity > Verbosity.SILENT) { - LOGGER.info("[RIFL] Loading RIFL specification from " + riflFileName); - } + LOGGER.info("[RIFL] Loading RIFL specification from {}", riflFileName); } if (cl.isSet(LAST)) { @@ -530,21 +507,9 @@ private static AbstractMediatorUserInterfaceControl createUserInterface(List Verbosity.SILENT) { - LOGGER.error("Auto mode was terminated by an exception:", e); - if (verbosity >= Verbosity.TRACE) { - e.printStackTrace(); - } - final String msg = e.getMessage(); - if (msg != null) { - LOGGER.info(msg); - } - } - System.exit(-1); - } + Thread.setDefaultUncaughtExceptionHandler((t, e) -> { + LOGGER.error("Auto mode was terminated by an exception:", e); + System.exit(-1); }); if (fileArguments.isEmpty()) { printUsageAndExit(true, "Error: No file to load from.", -4); @@ -552,8 +517,6 @@ public void uncaughtException(Thread t, Throwable e) { return new ConsoleUserInterfaceControl(verbosity, loadOnly); } else { - updateSplashScreen(); - /* explicitly enable pruning in closed branches for interactive mode * (if not manually disabled) */ GeneralSettings.noPruningClosed = cl.isSet(NO_PRUNING_CLOSED); @@ -569,7 +532,7 @@ public void uncaughtException(Thread t, Throwable e) { if (mostRecentFile.exists()) { fileArguments.add(mostRecentFile); } else { - LOGGER.info("File does not exist anymore: " + mostRecentFile.toString()); + LOGGER.info("File does not exist anymore: {}", mostRecentFile); } } } @@ -590,33 +553,15 @@ public static void ensureExamplesAvailable() { } } - private static void updateSplashScreen() { - try { - final java.awt.SplashScreen sp = java.awt.SplashScreen.getSplashScreen(); - if (sp == null) { - return; - // insert customization code here - // see http://docs.oracle.com/javase/tutorial/uiswing/misc/splashscreen.html - } - } catch (Exception e) { - } - } - private static void evaluateLemmataOptions(CommandLine options) { - LemmataAutoModeOptions opt; try { - - opt = new LemmataAutoModeOptions(options, KeYConstants.INTERNAL_VERSION, + LemmataAutoModeOptions opt = new LemmataAutoModeOptions(options, KeYConstants.INTERNAL_VERSION, PathConfig.getKeyConfigDir()); - LemmataHandler handler = new LemmataHandler(opt, - AbstractProfile.getDefaultProfile()); + LemmataHandler handler = new LemmataHandler(opt, AbstractProfile.getDefaultProfile()); handler.start(); - - } catch (Exception e) { - if (Debug.ENABLE_DEBUG) { - e.printStackTrace(); - } + } catch (IOException | ProofInputException e) { + LOGGER.error("Exception occured during the evaluation of lemmata options", e); printUsageAndExit(false, e.getMessage(), -2); } @@ -661,7 +606,7 @@ public static File getWorkingDir() { * Currently only performs RIFL to JML transformation. */ private static List preProcessInput(List filesOnStartup) { - List result = new ArrayList(); + List result = new ArrayList<>(); // RIFL to JML transformation if (riflFileName != null) { if (filesOnStartup.isEmpty()) { @@ -670,26 +615,16 @@ private static List preProcessInput(List filesOnStartup) { } // only use one input file File fileNameOnStartUp = filesOnStartup.get(0).getAbsoluteFile(); -// final KeYRecoderExceptionHandler kexh = ui.getMediator().getExceptionHandler(); try { RIFLTransformer transformer = new RIFLTransformer(); transformer.doTransform(riflFileName, fileNameOnStartUp, RIFLTransformer.getDefaultSavePath(fileNameOnStartUp)); - if (verbosity > Verbosity.SILENT) { - LOGGER.info("[RIFL] Writing transformed Java files to " + fileNameOnStartUp + " ..."); - } + LOGGER.info("[RIFL] Writing transformed Java files to {} ...", fileNameOnStartUp); return transformer.getProblemFiles(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } catch (ParserException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + } catch (ParserConfigurationException | SAXException | ParserException | IOException e) { + LOGGER.error("Exception occurred during pre-processing RIFL input", e); } - return result; } // nothing to do, pass the original files @@ -726,8 +661,7 @@ public static KeYDesktop getKeyDesktop() { * * @param keyDesktop The new {@link KeYDesktop} to use. */ - public static void setKeyDesktop(KeYDesktop keyDesktop) { - assert keyDesktop != null; - Main.keyDesktop = keyDesktop; + public static void setKeyDesktop(@Nonnull KeYDesktop keyDesktop) { + Main.keyDesktop = Objects.requireNonNull(keyDesktop); } } diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java b/key/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java index ac5e94bff6b..cabd160a700 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java @@ -26,16 +26,14 @@ import de.uka.ilkd.key.macros.ProofMacroFinishedInfo; import de.uka.ilkd.key.macros.SkipMacro; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; +import de.uka.ilkd.key.macros.scripts.ScriptException; import de.uka.ilkd.key.parser.Location; import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.ProofAggregate; import de.uka.ilkd.key.proof.Statistics; import de.uka.ilkd.key.proof.event.ProofDisposedEvent; -import de.uka.ilkd.key.proof.init.InitConfig; -import de.uka.ilkd.key.proof.init.ProblemInitializer; -import de.uka.ilkd.key.proof.init.Profile; -import de.uka.ilkd.key.proof.init.ProofOblInput; +import de.uka.ilkd.key.proof.init.*; import de.uka.ilkd.key.proof.io.ProblemLoader; import de.uka.ilkd.key.prover.ProverCore; import de.uka.ilkd.key.prover.TaskFinishedInfo; @@ -52,7 +50,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; import java.util.List; /** @@ -67,7 +68,7 @@ public class ConsoleUserInterfaceControl extends AbstractMediatorUserInterfaceCo // Substitute for TaskTree (GUI) to facilitate side proofs in console mode ImmutableList proofStack = ImmutableSLList.nil(); - final byte verbosity; + final int verbosity; final KeYMediator mediator; // for a progress bar @@ -92,8 +93,8 @@ public class ConsoleUserInterfaceControl extends AbstractMediatorUserInterfaceCo */ public boolean allProofsSuccessful = true; - public ConsoleUserInterfaceControl(byte verbosity, boolean loadOnly) { - this.verbosity = verbosity; + public ConsoleUserInterfaceControl(Verbosity verbosity, boolean loadOnly) { + this.verbosity = verbosity.ordinal(); this.mediator = new KeYMediator(this); this.loadOnly = loadOnly; } @@ -102,40 +103,32 @@ public ConsoleUserInterfaceControl(boolean verbose, boolean loadOnly) { this(verbose ? Verbosity.TRACE : Verbosity.NORMAL, loadOnly); } - private void printResults(final int openGoals, - TaskFinishedInfo info, - final Object result2) { - if (verbosity >= Verbosity.DEBUG) { - LOGGER.info("]"); // end progress bar + private void printResults(final int openGoals, TaskFinishedInfo info, final Object result2) { + if (verbosity >= Verbosity.DEBUG.ordinal()) { + System.out.println("]"); // end progress bar } - if (verbosity > Verbosity.SILENT) { - LOGGER.info("[ DONE ... rule application ]"); - if (verbosity >= Verbosity.DEBUG) { - LOGGER.info("\n== Proof " + (openGoals > 0 ? "open" : "closed") + " =="); - final Statistics stat = info.getProof().getStatistics(); - LOGGER.info("Proof steps: " + stat.nodes); - LOGGER.info("Branches: " + stat.branches); - LOGGER.info("Automode Time: " + stat.autoModeTimeInMillis + "ms"); - LOGGER.info("Time per step: " + stat.timePerStepInMillis + "ms"); - } - LOGGER.info("Number of goals remaining open: " + openGoals); - if (openGoals == 0) { - LOGGER.info("Proved"); - } else { - LOGGER.info("Not proved"); - } - System.out.flush(); + LOGGER.info("[ DONE ... rule application ]"); + LOGGER.debug("\n== Proof {} ==", openGoals > 0 ? "open" : "closed"); + final Statistics stat = info.getProof().getStatistics(); + LOGGER.debug("Proof steps: {}", stat.nodes); + LOGGER.debug("Branches: {}", stat.branches); + LOGGER.debug("Automode Time: {} ms", stat.autoModeTimeInMillis); + LOGGER.debug("Time per step: {} ms", stat.timePerStepInMillis); + LOGGER.info("Number of goals remaining open: {}", openGoals); + + if (openGoals == 0) { + LOGGER.info("Proved"); + } else { + LOGGER.info("Not proved"); } - // this seems to be a good place to free some memory - Runtime.getRuntime().gc(); /* * It is assumed that this part of the code is never reached, unless a * value has been assigned to keyProblemFile in method loadProblem(File). */ - assert keyProblemFile != null : "Unexcpected null pointer. Trying to" - + " save a proof but no corresponding key problem file is " - + "available."; + if (keyProblemFile == null) throw new IllegalStateException( + "Unexpected null pointer. Trying to save a proof but no corresponding key problem file is available."); + allProofsSuccessful &= saveProof(result2, info.getProof(), keyProblemFile); /* * We "delete" the value of keyProblemFile at this point by assigning @@ -155,12 +148,10 @@ public void taskFinished(TaskFinishedInfo info) { progressMax = 0; // reset progress bar marker final Proof proof = info.getProof(); if (proof == null) { - if (verbosity > Verbosity.SILENT) { - LOGGER.info("Proof loading failed"); - final Object error = info.getResult(); - if (error instanceof Throwable) { - ((Throwable) error).printStackTrace(); - } + LOGGER.error("Proof loading failed"); + final Object error = info.getResult(); + if (error instanceof Throwable) { + LOGGER.info("Exception is", (Throwable) error); } System.exit(1); } @@ -176,7 +167,7 @@ public void taskFinished(TaskFinishedInfo info) { System.exit(-1); } if (loadOnly || openGoals == 0) { - LOGGER.info("Number of open goals after loading: " + openGoals); + LOGGER.info("Number of open goals after loading: {}", openGoals); System.exit(0); } ProblemLoader problemLoader = (ProblemLoader) info.getSource(); @@ -190,8 +181,8 @@ public void taskFinished(TaskFinishedInfo info) { // The start and end messages are fake to persuade the system ... // All this here should refactored anyway ... this.taskFinished(new ProofMacroFinishedInfo(new SkipMacro(), proof)); - } catch (Exception e) { - LOGGER.debug("", e); + } catch (IOException | InterruptedException | ScriptException | ProofInputException e) { + LOGGER.error("Excepton occured", e); System.exit(-1); } } else if (macroChosen()) { @@ -206,10 +197,9 @@ public void taskFinished(TaskFinishedInfo info) { public void taskStarted(TaskStartedInfo info) { super.taskStarted(info); progressMax = info.getSize(); + LOGGER.debug(info.getMessage()); if (TaskKind.Strategy.equals(info.getKind())) { - LOGGER.debug(info.getMessage() + " ["); // start progress bar - } else { - LOGGER.debug(info.getMessage()); + System.out.print("["); // start progress bar } } @@ -265,39 +255,39 @@ void finish(Proof proof) { } @Override - final public void progressStarted(Object sender) { - LOGGER.debug("ConsoleUserInterfaceControl.progressStarted(" + sender + ")"); + public final void progressStarted(Object sender) { + LOGGER.debug("ConsoleUserInterfaceControl.progressStarted({})", sender); } @Override - final public void progressStopped(Object sender) { - LOGGER.debug("ConsoleUserInterfaceControl.progressStopped(" + sender + ")"); + public final void progressStopped(Object sender) { + LOGGER.debug("ConsoleUserInterfaceControl.progressStopped({})", sender); } @Override - final public void reportException(Object sender, ProofOblInput input, Exception e) { + public final void reportException(Object sender, ProofOblInput input, Exception e) { LOGGER.debug("ConsoleUserInterfaceControl.reportException({},{},{})", sender, input, e); } @Override - final public void reportStatus(Object sender, String status, int progress) { - LOGGER.debug("ConsoleUserInterfaceControl.reportStatus(" + sender + "," + status + "," + progress + ")"); + public final void reportStatus(Object sender, String status, int progress) { + LOGGER.debug("ConsoleUserInterfaceControl.reportStatus({},{},{})", sender, status, progress); } @Override - final public void reportStatus(Object sender, String status) { - LOGGER.debug("ConsoleUserInterfaceControl.reportStatus(" + sender + "," + status + ")"); + public final void reportStatus(Object sender, String status) { + LOGGER.debug("ConsoleUserInterfaceControl.reportStatus({},{})", sender, status); } @Override - final public void resetStatus(Object sender) { - LOGGER.debug("ConsoleUserInterfaceControl.resetStatus(" + sender + ")"); + public final void resetStatus(Object sender) { + LOGGER.debug("ConsoleUserInterfaceControl.resetStatus({})", sender); } @Override - final public void taskProgress(int position) { + public final void taskProgress(int position) { super.taskProgress(position); - if (verbosity >= Verbosity.DEBUG && progressMax > 0) { + if (verbosity >= Verbosity.DEBUG.ordinal() && progressMax > 0) { if ((position * PROGRESS_BAR_STEPS) % progressMax == 0) { System.out.print(PROGRESS_MARK); } @@ -305,13 +295,13 @@ final public void taskProgress(int position) { } @Override - final public void setMaximum(int maximum) { - LOGGER.debug("ConsoleUserInterfaceControl.setMaximum(" + maximum + ")"); + public final void setMaximum(int maximum) { + LOGGER.debug("ConsoleUserInterfaceControl.setMaximum({})",maximum); } @Override - final public void setProgress(int progress) { - LOGGER.debug("ConsoleUserInterfaceControl.setProgress(" + progress + ")"); + public final void setProgress(int progress) { + LOGGER.debug("ConsoleUserInterfaceControl.setProgress({})", progress); } @Override @@ -320,16 +310,13 @@ public void completeAndApplyTacletMatch(TacletInstantiationModel[] models, Goal } @Override - final public void openExamples() { + public final void openExamples() { LOGGER.info("Open Examples not suported by console UI."); } @Override - final public ProblemInitializer createProblemInitializer(Profile profile) { - ProblemInitializer pi = new ProblemInitializer(this, - new Services(profile), - this); - return pi; + public final ProblemInitializer createProblemInitializer(Profile profile) { + return new ProblemInitializer(this, new Services(profile), this); } /** @@ -341,7 +328,9 @@ public void proofDisposing(ProofDisposedEvent e) { if (!proofStack.isEmpty()) { Proof p = proofStack.head(); proofStack = proofStack.removeAll(p); - assert p.name().equals(e.getSource().name()); + if (!p.name().equals(e.getSource().name())) { + throw new AssertionError(); + } mediator.setProof(proofStack.head()); } else { // proofStack might be empty, though proof != null. This can @@ -351,7 +340,7 @@ public void proofDisposing(ProofDisposedEvent e) { } @Override - final public boolean selectProofObligation(InitConfig initConfig) { + public final boolean selectProofObligation(InitConfig initConfig) { ProofObligationSelector sel = new ConsoleProofObligationSelector(this, initConfig); return sel.selectProofObligation(); } @@ -393,7 +382,7 @@ public void reportWarnings(ImmutableSet warnings) { public static boolean saveProof(Object result, Proof proof, File keyProblemFile) { if (result instanceof Throwable) { - throw new RuntimeException("Error in batchmode.", (Throwable) result); + throw new IllegalStateException("Error occured while running in batch mode.", (Throwable) result); } // Save the proof before exit. @@ -420,16 +409,13 @@ public static boolean saveProof(Object result, Proof proof, // save proof statistics ShowProofStatistics.getCSVStatisticsMessage(proof); File file = new File(MiscTools.toValidFileName(proof.name().toString()) + ".csv"); - try (BufferedWriter writer = - new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); - ) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(ShowProofStatistics.getCSVStatisticsMessage(proof)); } catch (IOException e) { - e.printStackTrace(); - assert false; + LOGGER.error("Error occurred while writing CSV statistics", e); } } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("Error occurred while writing proof files to {}", f.getAbsolutePath(), e); } // Says true if all Proofs have succeeded, // or false if there is at least one open Proof diff --git a/key/key.ui/src/main/java/de/uka/ilkd/key/ui/Verbosity.java b/key/key.ui/src/main/java/de/uka/ilkd/key/ui/Verbosity.java index cdef2ddf6f1..f228fb3786b 100644 --- a/key/key.ui/src/main/java/de/uka/ilkd/key/ui/Verbosity.java +++ b/key/key.ui/src/main/java/de/uka/ilkd/key/ui/Verbosity.java @@ -1,9 +1,5 @@ package de.uka.ilkd.key.ui; -public interface Verbosity { - byte SILENT = 0; - byte NORMAL = 1; - byte INFO = 2; - byte DEBUG = 3; - byte TRACE = 4; +public enum Verbosity { + SILENT, NORMAL, INFO, DEBUG, TRACE } diff --git a/key/key.util/src/main/java/org/key_project/util/ExtList.java b/key/key.util/src/main/java/org/key_project/util/ExtList.java index 6dd4b0b9dfd..344b32735b3 100644 --- a/key/key.util/src/main/java/org/key_project/util/ExtList.java +++ b/key/key.util/src/main/java/org/key_project/util/ExtList.java @@ -14,89 +14,100 @@ package org.key_project.util; -import java.util.Iterator; -import java.util.LinkedList; +import java.util.*; -/** extends java.util.LinkedList in order to collect elements - * according to their type */ -public class ExtList extends LinkedList { - - private static final long serialVersionUID = 9182017368310263908L; - +/** + * extends java.util.LinkedList in order to collect elements + * according to their type + */ +public class ExtList extends ArrayList { public ExtList() { super(); } - - public ExtList(Object[] a){ - super(); - for (Object o: a) add(o); + + public ExtList(Object[] a) { + addAll(Arrays.asList(a)); } - /** copies list to array (array has type of cl) */ - private static T[] toArray(Class cl, LinkedList list) { + public ExtList(int size) { + super(size); + } + + /** + * copies list to array (array has type of cl) + */ + private static T[] toArray(Class cl, List list) { @SuppressWarnings("unchecked") - T[] array= (T[]) java.lang.reflect.Array.newInstance(cl,list.size()); - System.arraycopy(list.toArray(),0,array,0,list.size()); + T[] array = (T[]) java.lang.reflect.Array.newInstance(cl, list.size()); + System.arraycopy(list.toArray(), 0, array, 0, list.size()); return array; } /** * collects (non-null) elements of the classtype cl and returns a typed array + * * @param cl Class the type of the elements that are selected * @return array with type cl */ @SuppressWarnings("unchecked") - public T[] collect(Class cl) { - LinkedList colls=new LinkedList(); - for (Object next: this) { - if (cl.isInstance(next) && (next!=null)) { - colls.add((T)next); - } + public T[] collect(Class cl) { + List colls = new ArrayList<>(size()); + for (Object next : this) { + if (cl.isInstance(next) && (next != null)) { + colls.add((T) next); + } } - - return toArray(cl,colls); - + return toArray(cl, colls); } /** * returns first element in list of type cl + * * @param cl the type to be searched in list * @return the first element with type cl in list */ @SuppressWarnings("unchecked") - public T get(Class cl) { - Iterator it=iterator(); - while(it.hasNext()) { - Object next=it.next(); - if (cl.isInstance(next) && (next!=null)) { - return (T)next; - } + public T get(Class cl) { + for (Object next : this) { + if (cl.isInstance(next) && (next != null)) { + return (T) next; + } } - - return null; + return null; } /** * returns first element in list of type cl and removes the found * element from the list if the elemnt has not been found null * is returned + * * @param cl the type to be searched in list * @return the first element with type cl in list */ @SuppressWarnings("unchecked") - public T removeFirstOccurrence(Class cl) { + public T removeFirstOccurrence(Class cl) { Iterator it = iterator(); - while(it.hasNext()) { + while (it.hasNext()) { Object next = it.next(); - if (cl.isInstance(next) && (next!=null)) { + if (cl.isInstance(next) && (next != null)) { it.remove(); - return (T)next; - } + return (T) next; + } } - return null; + return null; } + public Object getFirst() { + return get(0); + } + public void addFirst(Object o) { + add(0, o); + } + + public Object removeFirst() { + return remove(0); + } } \ No newline at end of file diff --git a/key/key.util/src/main/java/org/key_project/util/java/IOUtil.java b/key/key.util/src/main/java/org/key_project/util/java/IOUtil.java index 373f2e256ac..03c1e0a91b4 100644 --- a/key/key.util/src/main/java/org/key_project/util/java/IOUtil.java +++ b/key/key.util/src/main/java/org/key_project/util/java/IOUtil.java @@ -874,7 +874,7 @@ public static void extractZip(Path archive, Path targetDir) throws IOException { } - private static Pattern URL_JAR_FILE = Pattern.compile("jar:file:([^!]+)!/(.+)"); + public static final Pattern URL_JAR_FILE = Pattern.compile("jar:file:([^!]+)!/(.+)"); /** * Tries to open a stream with the given file name. From 33cef7c0e9b017f2e10b0972c6255f7147ab6935 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 8 Mar 2022 01:08:27 +0100 Subject: [PATCH 007/225] wip on class hierarchy --- .../CcatchBreakLabelParameterDeclaration.java | 7 + .../java/CcatchBreakParameterDeclaration.java | 14 +- ...atchBreakWildcardParameterDeclaration.java | 6 + ...atchContinueLabelParameterDeclaration.java | 7 + .../CcatchContinueParameterDeclaration.java | 11 +- ...hContinueWildcardParameterDeclaration.java | 14 +- ...CcatchNonstandardParameterDeclaration.java | 5 + .../CcatchReturnParameterDeclaration.java | 14 +- .../CcatchReturnValParameterDeclaration.java | 22 +- .../de/uka/ilkd/key/java/CompilationUnit.java | 215 ++++++----- .../java/de/uka/ilkd/key/java/Import.java | 166 ++++---- .../java/JavaNonTerminalProgramElement.java | 170 ++++---- .../uka/ilkd/key/java/JavaProgramElement.java | 166 ++++---- .../uka/ilkd/key/java/JavaSourceElement.java | 206 +++++----- .../key/java/NonTerminalProgramElement.java | 30 +- .../ilkd/key/java/PackageSpecification.java | 71 ++-- .../de/uka/ilkd/key/java/PositionInfo.java | 61 ++- .../de/uka/ilkd/key/java/StatementBlock.java | 184 ++++----- .../java/declaration/ClassInitializer.java | 2 + .../declaration/ConstructorDeclaration.java | 107 ++--- .../java/declaration/FieldDeclaration.java | 108 +++--- .../declaration/InheritanceSpecification.java | 96 ++--- .../key/java/declaration/JavaDeclaration.java | 119 +++--- .../java/declaration/MethodDeclaration.java | 268 +++++++------ .../uka/ilkd/key/java/declaration/Throws.java | 120 +++--- .../key/java/declaration/TypeDeclaration.java | 4 + .../java/declaration/VariableDeclaration.java | 115 +++--- .../declaration/VariableSpecification.java | 4 + .../key/java/expression/ArrayInitializer.java | 116 +++--- .../ilkd/key/java/expression/Assignment.java | 108 +++--- .../uka/ilkd/key/java/expression/Literal.java | 74 ++-- .../ilkd/key/java/expression/Operator.java | 209 +++++----- .../expression/ParenthesizedExpression.java | 96 +++-- .../literal/AbstractIntegerLiteral.java | 23 +- .../expression/literal/BooleanLiteral.java | 105 ++--- .../java/expression/literal/CharLiteral.java | 95 +++-- .../expression/literal/DoubleLiteral.java | 97 +++-- .../java/expression/literal/IntLiteral.java | 49 ++- .../java/expression/literal/LongLiteral.java | 50 ++- .../java/expression/literal/NullLiteral.java | 29 +- .../java/expression/operator/BinaryAnd.java | 48 +-- .../operator/BinaryAndAssignment.java | 47 ++- .../java/expression/operator/BinaryNot.java | 64 +-- .../expression/operator/BinaryOperator.java | 48 ++- .../java/expression/operator/BinaryOr.java | 43 ++- .../operator/BinaryOrAssignment.java | 41 +- .../java/expression/operator/BinaryXOr.java | 42 +- .../operator/BinaryXOrAssignment.java | 47 ++- .../operator/ComparativeOperator.java | 52 +-- .../java/expression/operator/Conditional.java | 140 +++---- .../expression/operator/CopyAssignment.java | 42 +- .../key/java/expression/operator/Divide.java | 41 +- .../expression/operator/DivideAssignment.java | 48 ++- .../key/java/expression/operator/Equals.java | 38 +- .../expression/operator/ExactInstanceof.java | 3 + .../expression/operator/GreaterOrEquals.java | 35 +- .../java/expression/operator/GreaterThan.java | 35 +- .../java/expression/operator/Instanceof.java | 80 ++-- .../java/expression/operator/Intersect.java | 17 +- .../expression/operator/LessOrEquals.java | 34 +- .../java/expression/operator/LessThan.java | 31 +- .../java/expression/operator/LogicalAnd.java | 58 ++- .../java/expression/operator/LogicalNot.java | 57 +-- .../java/expression/operator/LogicalOr.java | 51 ++- .../key/java/expression/operator/Minus.java | 44 ++- .../expression/operator/MinusAssignment.java | 9 + .../key/java/expression/operator/Modulo.java | 40 +- .../expression/operator/ModuloAssignment.java | 45 ++- .../java/expression/operator/Negative.java | 63 +-- .../key/java/expression/operator/New.java | 8 +- .../java/expression/operator/NewArray.java | 3 + .../java/expression/operator/NotEquals.java | 35 +- .../key/java/expression/operator/Plus.java | 37 +- .../expression/operator/PlusAssignment.java | 48 ++- .../java/expression/operator/Positive.java | 66 ++-- .../expression/operator/PostDecrement.java | 41 +- .../expression/operator/PostIncrement.java | 45 ++- .../expression/operator/PreDecrement.java | 47 ++- .../expression/operator/PreIncrement.java | 43 ++- .../java/expression/operator/ShiftLeft.java | 69 ++-- .../operator/ShiftLeftAssignment.java | 53 +-- .../java/expression/operator/ShiftRight.java | 71 ++-- .../operator/ShiftRightAssignment.java | 55 +-- .../key/java/expression/operator/Times.java | 9 + .../expression/operator/TimesAssignment.java | 56 +-- .../expression/operator/TypeOperator.java | 81 ++-- .../operator/UnsignedShiftRight.java | 70 ++-- .../UnsignedShiftRightAssignment.java | 53 +-- .../expression/operator/adt/SeqConcat.java | 15 +- .../expression/operator/adt/SetMinus.java | 16 +- .../expression/operator/adt/SetUnion.java | 16 +- .../java/reference/ArrayLengthReference.java | 102 ++--- .../key/java/reference/ArrayReference.java | 224 ++++++----- .../key/java/reference/ExecutionContext.java | 30 +- .../key/java/reference/FieldReference.java | 140 ++++--- .../java/reference/MetaClassReference.java | 118 +++--- .../key/java/reference/MethodReference.java | 316 ++++++++------- .../key/java/reference/PackageReference.java | 144 ++++--- .../reference/SchematicFieldReference.java | 140 +++---- .../SpecialConstructorReference.java | 107 ++--- .../reference/SuperConstructorReference.java | 5 +- .../key/java/reference/SuperReference.java | 122 +++--- .../key/java/reference/ThisReference.java | 123 +++--- .../key/java/reference/TypeReferenceImp.java | 188 ++++----- .../key/java/reference/VariableReference.java | 62 +-- .../ilkd/key/java/statement/BranchImp.java | 32 +- .../key/java/statement/BranchStatement.java | 30 +- .../de/uka/ilkd/key/java/statement/Break.java | 42 +- .../de/uka/ilkd/key/java/statement/Case.java | 126 +++--- .../de/uka/ilkd/key/java/statement/Catch.java | 129 +++---- .../key/java/statement/CatchAllStatement.java | 124 +++--- .../uka/ilkd/key/java/statement/Ccatch.java | 134 +++---- .../uka/ilkd/key/java/statement/Continue.java | 38 +- .../uka/ilkd/key/java/statement/Default.java | 86 +++-- .../de/uka/ilkd/key/java/statement/Do.java | 56 +-- .../de/uka/ilkd/key/java/statement/Else.java | 87 +++-- .../key/java/statement/EmptyStatement.java | 45 ++- .../ilkd/key/java/statement/EnhancedFor.java | 3 + .../de/uka/ilkd/key/java/statement/Exec.java | 92 ++--- .../statement/ExpressionJumpStatement.java | 82 ++-- .../uka/ilkd/key/java/statement/Finally.java | 84 ++-- .../de/uka/ilkd/key/java/statement/For.java | 3 + .../ilkd/key/java/statement/ForUpdates.java | 60 +-- .../de/uka/ilkd/key/java/statement/Guard.java | 43 ++- .../de/uka/ilkd/key/java/statement/If.java | 126 +++--- .../key/java/statement/JavaStatement.java | 28 +- .../key/java/statement/JumpStatement.java | 24 +- .../java/statement/LabelJumpStatement.java | 86 +++-- .../key/java/statement/LabeledStatement.java | 287 +++++++------- .../uka/ilkd/key/java/statement/LoopInit.java | 63 ++- .../key/java/statement/LoopScopeBlock.java | 108 +++--- .../key/java/statement/LoopStatement.java | 364 +++++++++--------- .../java/statement/MergePointStatement.java | 64 ++- .../java/statement/MethodBodyStatement.java | 298 +++++++------- .../ilkd/key/java/statement/MethodFrame.java | 230 ++++++----- .../uka/ilkd/key/java/statement/Return.java | 39 +- .../uka/ilkd/key/java/statement/Switch.java | 122 +++--- .../key/java/statement/SynchronizedBlock.java | 167 ++++---- .../de/uka/ilkd/key/java/statement/Then.java | 69 ++-- .../de/uka/ilkd/key/java/statement/Throw.java | 34 +- .../java/statement/TransactionStatement.java | 49 +-- .../de/uka/ilkd/key/java/statement/Try.java | 165 ++++---- .../de/uka/ilkd/key/java/statement/While.java | 3 + .../de/uka/ilkd/key/parser/ParserUtil.java | 2 +- .../metaconstruct/ProgramTransformer.java | 198 +++++----- .../de/uka/ilkd/key/java/JP2KeyConverter.java | 233 +++++++---- .../java/org/key_project/util/ExtList.java | 22 +- 147 files changed, 6130 insertions(+), 5411 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakLabelParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakLabelParameterDeclaration.java index a3027be73c0..7be7dfc4b13 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakLabelParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakLabelParameterDeclaration.java @@ -14,6 +14,7 @@ package de.uka.ilkd.key.java; import java.io.IOException; +import java.util.List; import org.key_project.util.ExtList; @@ -29,7 +30,13 @@ public class CcatchBreakLabelParameterDeclaration private final Label label; + public CcatchBreakLabelParameterDeclaration(PositionInfo pi, List comments, Label label) { + super(pi, comments); + this.label = label; + } + public CcatchBreakLabelParameterDeclaration(ExtList children) { + super(null, null); label = children.get(Label.class); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakParameterDeclaration.java index e6e016ef8b5..60e643b14dd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakParameterDeclaration.java @@ -13,21 +13,25 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.io.IOException; +import java.util.List; /** * A "\Break" parameter declaration of a ccatch clause. * * @author Dominic Steinhöfel */ -public class CcatchBreakParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakParameterDeclaration extends CcatchNonstandardParameterDeclaration { + + public CcatchBreakParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } public CcatchBreakParameterDeclaration(ExtList children) { + super(null, null); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakWildcardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakWildcardParameterDeclaration.java index 8198ae5db5c..b0bcafd2588 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakWildcardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchBreakWildcardParameterDeclaration.java @@ -14,6 +14,7 @@ package de.uka.ilkd.key.java; import java.io.IOException; +import java.util.List; import org.key_project.util.ExtList; @@ -27,7 +28,12 @@ public class CcatchBreakWildcardParameterDeclaration extends CcatchNonstandardParameterDeclaration { + public CcatchBreakWildcardParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } + public CcatchBreakWildcardParameterDeclaration(ExtList children) { + super(null,null); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueLabelParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueLabelParameterDeclaration.java index 7623f1a170a..fb952aa44ba 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueLabelParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueLabelParameterDeclaration.java @@ -14,6 +14,7 @@ package de.uka.ilkd.key.java; import java.io.IOException; +import java.util.List; import org.key_project.util.ExtList; @@ -29,7 +30,13 @@ public class CcatchContinueLabelParameterDeclaration private final Label label; + public CcatchContinueLabelParameterDeclaration(PositionInfo pi, List comments, Label label) { + super(pi, comments); + this.label = label; + } + public CcatchContinueLabelParameterDeclaration(ExtList children) { + super(null, null); label = children.get(Label.class); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueParameterDeclaration.java index acf5d04adce..dffdff9ce22 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueParameterDeclaration.java @@ -13,11 +13,11 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.io.IOException; +import java.util.List; /** * A "\Continue" parameter declaration of a ccatch clause. @@ -27,7 +27,12 @@ public class CcatchContinueParameterDeclaration extends CcatchNonstandardParameterDeclaration { + public CcatchContinueParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } + public CcatchContinueParameterDeclaration(ExtList children) { + super(null, null); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueWildcardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueWildcardParameterDeclaration.java index 58a2ef28406..e4b9d2007e2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueWildcardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchContinueWildcardParameterDeclaration.java @@ -13,21 +13,25 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.io.IOException; +import java.util.List; /** * A "\Continue *" parameter declaration of a ccatch clause. * * @author Dominic Steinhöfel */ -public class CcatchContinueWildcardParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchContinueWildcardParameterDeclaration extends CcatchNonstandardParameterDeclaration { + + public CcatchContinueWildcardParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } public CcatchContinueWildcardParameterDeclaration(ExtList children) { + super(null, null); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchNonstandardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchNonstandardParameterDeclaration.java index dd819404c17..60783bdc111 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchNonstandardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchNonstandardParameterDeclaration.java @@ -13,6 +13,8 @@ package de.uka.ilkd.key.java; +import java.util.List; + /** * A "non-standard" parameter declaration of a Ccatch clause, e.g., "\Return". * @@ -21,4 +23,7 @@ public abstract class CcatchNonstandardParameterDeclaration extends JavaNonTerminalProgramElement { + public CcatchNonstandardParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnParameterDeclaration.java index c30a26b0af1..9884392455c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnParameterDeclaration.java @@ -13,21 +13,25 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.io.IOException; +import java.util.List; /** * A "\Return" parameter declaration of a ccatch clause. * * @author Dominic Steinhöfel */ -public class CcatchReturnParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchReturnParameterDeclaration extends CcatchNonstandardParameterDeclaration { + + public CcatchReturnParameterDeclaration(PositionInfo pi, List comments) { + super(pi, comments); + } public CcatchReturnParameterDeclaration(ExtList children) { + super(null, null); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnValParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnValParameterDeclaration.java index 344fc82bb4a..00fb5014039 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnValParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CcatchReturnValParameterDeclaration.java @@ -13,15 +13,15 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - import de.uka.ilkd.key.java.declaration.ParameterDeclaration; import de.uka.ilkd.key.java.declaration.VariableSpecification; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.rule.MatchConditions; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import java.io.IOException; +import java.util.List; /** * A "\Return int v" parameter declaration of a ccatch clause. @@ -33,7 +33,13 @@ public class CcatchReturnValParameterDeclaration extends private final ParameterDeclaration delegate; + public CcatchReturnValParameterDeclaration(PositionInfo pi, List comments, ParameterDeclaration delegate) { + super(pi, comments); + this.delegate = delegate; + } + public CcatchReturnValParameterDeclaration(ExtList children) { + super(null, null); delegate = children.get(ParameterDeclaration.class); } @@ -63,11 +69,9 @@ public int getChildCount() { * Returns the child at the specified index in this node's "virtual" child * array * - * @param index - * an index into this node's "virtual" child array + * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CompilationUnit.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CompilationUnit.java index f1a62289bbe..3ecdfce5c80 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CompilationUnit.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CompilationUnit.java @@ -14,153 +14,173 @@ package de.uka.ilkd.key.java; -import java.io.IOException; -import java.io.StringWriter; - -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - import de.uka.ilkd.key.java.declaration.TypeDeclaration; import de.uka.ilkd.key.java.declaration.TypeDeclarationContainer; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.StringWriter; +import java.util.Collections; +import java.util.List; + /** - * A node representing a single source file containing - * {@link TypeDeclaration}s and an optional {@link PackageSpecification} - * and an optional set of {@link Import}s. In Java, any source file - * may contain at most one public class type definition. - * This class is taken from COMPOST and changed so that it can be - * used as an immutable class + * A node representing a single source file containing + * {@link TypeDeclaration}s and an optional {@link PackageSpecification} + * and an optional set of {@link Import}s. In Java, any source file + * may contain at most one public class type definition. + * This class is taken from COMPOST and changed so that it can be + * used as an immutable class */ -public class CompilationUnit extends JavaNonTerminalProgramElement implements TypeDeclarationContainer, TypeScope { +public final class CompilationUnit extends JavaNonTerminalProgramElement + implements TypeDeclarationContainer, TypeScope { private static final Logger LOGGER = LoggerFactory.getLogger(CompilationUnit.class); /** * Package spec. */ - - protected final PackageSpecification packageSpec; + @Nullable + private final PackageSpecification packageSpec; /** * Imports. */ - - protected final ImmutableArray imports; + @Nonnull + private final ImmutableArray imports; /** * Type declarations. */ - protected final ImmutableArray typeDeclarations; + @Nonnull + private final ImmutableArray typeDeclarations; - /** creates a compilation unit - * @param packageSpec a PackageSpecification (pck of this CU) - * @param imports an array of Import (all it imports) - * @param typeDeclarations an array of TypeDeclaration (the - * type declared in it) + /** + * creates a compilation unit + * + * @param packageSpec a PackageSpecification (pck of this CU) + * @param imports an array of Import (all it imports) + * @param typeDeclarations an array of TypeDeclaration (the + * type declared in it) */ - public CompilationUnit(PackageSpecification packageSpec, Import[] - imports, - TypeDeclaration[] typeDeclarations) - { - this.packageSpec=packageSpec; - this.imports=new ImmutableArray(imports); - this.typeDeclarations=new ImmutableArray(typeDeclarations); + public CompilationUnit(PackageSpecification packageSpec, Import[] imports, TypeDeclaration[] typeDeclarations) { + this(null, Collections.emptyList(), packageSpec, + new ImmutableArray<>(imports), new ImmutableArray<>(typeDeclarations)); } + public CompilationUnit(@Nullable PositionInfo pi, @Nullable List comments, + @Nullable PackageSpecification packageSpec, + @Nonnull ImmutableArray imports, + @Nonnull ImmutableArray typeDeclarations) { + super(pi, comments); + this.packageSpec = packageSpec; + this.imports = imports; + this.typeDeclarations = typeDeclarations; + } - /** creates a compilation unit + /** + * creates a compilation unit + * * @param children list with the children of this unit */ public CompilationUnit(ExtList children) { - super(children); - packageSpec=children.get(PackageSpecification.class); - this.imports=new ImmutableArray(children.collect(Import.class)); - this.typeDeclarations=new - ImmutableArray(children.collect(TypeDeclaration.class)); + super(children); + packageSpec = children.get(PackageSpecification.class); + this.imports = new ImmutableArray<>(children.collect(Import.class)); + this.typeDeclarations = new + ImmutableArray<>(children.collect(TypeDeclaration.class)); } - + + @Override + @Nonnull public SourceElement getFirstElement() { return (getChildCount() > 0) ? getChildAt(0).getFirstElement() : this; } @Override public SourceElement getFirstElementIncludingBlocks() { - return (getChildCount() > 0) ? getChildAt(0).getFirstElementIncludingBlocks() : this; + return (getChildCount() > 0) ? getChildAt(0).getFirstElementIncludingBlocks() : this; } + @Override + @Nonnull public SourceElement getLastElement() { return - typeDeclarations.get(typeDeclarations.size()-1); + typeDeclarations.get(typeDeclarations.size() - 1); } /** - * Get name of the unit. The name is empty if no data location is set; - * otherwise, the name of the current data location is returned. - * @return the name of this compilation unit. - * + * Get name of the unit. The name is empty if no data location is set; + * otherwise, the name of the current data location is returned. + * + * @return the name of this compilation unit. */ public String getName() { return ""; //(location == null) ? "" : location.toString(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ + @Override public int getChildCount() { int result = 0; - if (packageSpec != null) result++; - if (imports != null) result += imports.size(); - if (typeDeclarations != null) result += typeDeclarations.size(); + if (packageSpec != null) result++; + result += imports.size(); + result += typeDeclarations.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ + @Override public ProgramElement getChildAt(int index) { int len; if (packageSpec != null) { if (index == 0) return packageSpec; index--; } - if (imports != null) { - len = imports.size(); - if (len > index) { - return imports.get(index); - } - index -= len; - } - if (typeDeclarations != null) { - return typeDeclarations.get(index); + len = imports.size(); + if (len > index) { + return imports.get(index); } - throw new ArrayIndexOutOfBoundsException(); + index -= len; + return typeDeclarations.get(index); } /** - * Get imports. - * @return the wrapped import array. + * Get imports. + * + * @return the wrapped import array. */ + @Nonnull public ImmutableArray getImports() { return imports; } /** - * Get package specification. - * @return the package specification. + * Get package specification. + * + * @return the package specification. */ public PackageSpecification getPackageSpecification() { @@ -169,13 +189,14 @@ public PackageSpecification getPackageSpecification() { /** - * Get the number of type declarations in this container. - * @return the number of type declarations. + * Get the number of type declarations in this container. + * + * @return the number of type declarations. */ + @Override public int getTypeDeclarationCount() { - return (typeDeclarations != null) ? - typeDeclarations.size() : 0; + return typeDeclarations.size(); } /* @@ -187,16 +208,15 @@ public int getTypeDeclarationCount() { of bounds. */ + @Override public TypeDeclaration getTypeDeclarationAt(int index) { - if (typeDeclarations != null) { - return typeDeclarations.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return typeDeclarations.get(index); } /** - * Get declarations. - * @return the wrapped array of type declarations . + * Get declarations. + * + * @return the wrapped array of type declarations . */ public ImmutableArray getDeclarations() { return typeDeclarations; @@ -205,13 +225,13 @@ public ImmutableArray getDeclarations() { /** * Gets the primary type declaration of the compilation unit. * The primary declaration is the first declaration of the unit, - * or the single public declaration. If there is no unambiguous primary + * or the single public declaration. If there is no unambiguous primary * declaration, this method returns null. */ public TypeDeclaration getPrimaryTypeDeclaration() { TypeDeclaration res = null; - int s = typeDeclarations.size(); + int s = typeDeclarations.size(); for (int i = 0; i < s; i += 1) { TypeDeclaration t = typeDeclarations.get(i); if (t.isPublic()) { @@ -230,29 +250,36 @@ public TypeDeclaration getPrimaryTypeDeclaration() { return res; } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printCompilationUnit(this); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnCompilationUnit(this); + v.performActionOnCompilationUnit(this); } - /** toString */ + /** + * toString + */ + @Override public String toString() { - StringWriter sw = new StringWriter(); - try { - PrettyPrinter pp=new PrettyPrinter(sw); - pp.setIndentationLevel(3); - prettyPrint(pp); - } catch (IOException e) { - LOGGER.error("Pretty printing of compilation unit failed", e); - } - return sw.toString(); + StringWriter sw = new StringWriter(); + try { + PrettyPrinter pp = new PrettyPrinter(sw); + pp.setIndentationLevel(3); + prettyPrint(pp); + } catch (IOException e) { + LOGGER.error("Pretty printing of compilation unit failed", e); + } + return sw.toString(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Import.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Import.java index aea562be89f..10589bb6c42 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Import.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Import.java @@ -13,81 +13,81 @@ package de.uka.ilkd.key.java; +import de.uka.ilkd.key.java.reference.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.reference.PackageReference; -import de.uka.ilkd.key.java.reference.PackageReferenceContainer; -import de.uka.ilkd.key.java.reference.TypeReference; -import de.uka.ilkd.key.java.reference.TypeReferenceContainer; -import de.uka.ilkd.key.java.reference.TypeReferenceInfix; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; + /** - * Import. - * + * Import. */ -public class Import extends JavaNonTerminalProgramElement - implements TypeReferenceContainer, PackageReferenceContainer { +public final class Import extends JavaNonTerminalProgramElement + implements TypeReferenceContainer, PackageReferenceContainer { /** - * Multi import flag. + * Multi import flag. */ + private final boolean isMultiImport; - protected final boolean isMultiImport; - - /** - * Type reference infix. - */ - protected final TypeReferenceInfix reference; - /** - * children may contain: TypeReference (for import), a Comment - * @param isMultiImport indicates whether the import contains multiple - * imports + * Type reference infix. */ - public Import(ExtList children, boolean isMultiImport) { - super(children); - reference=children.get(TypeReferenceInfix.class); - this.isMultiImport=isMultiImport; + @Nonnull + private final TypeReferenceInfix reference; + + public Import(PositionInfo pi, List comments, boolean isMultiImport, + @Nonnull TypeReferenceInfix reference) { + super(pi, comments); + this.isMultiImport = isMultiImport; + this.reference = reference; } - /** - * Import. + * children may contain: TypeReference (for import), a Comment + * + * @param isMultiImport indicates whether the import contains multiple + * imports */ - public Import() { - isMultiImport=false; - reference=null; + @Deprecated + public Import(ExtList children, boolean isMultiImport) { + super(children); + reference = children.get(TypeReferenceInfix.class); + this.isMultiImport = isMultiImport; } /** - * Import. - * @param t a type reference. - * @param multi indicates the wildcard. + * Import. + * + * @param t a type reference. + * @param multi indicates the wildcard. */ public Import(TypeReference t, boolean multi) { - reference=t; - isMultiImport=multi; + this(null, null, multi, t); } /** - * Import. - * @param t a package reference. + * Import. + * + * @param t a package reference. */ - public Import(PackageReference t) { - reference=t; - isMultiImport=true; + this(null, null, true, t); } + @Override + @Nonnull public SourceElement getLastElement() { return reference; } /** - * Checks if this import is a multi type import, also known as - * type-on-demand import. - * @return the kind of this import. + * Checks if this import is a multi type import, also known as + * type-on-demand import. + * + * @return the kind of this import. */ public boolean isMultiImport() { @@ -95,35 +95,39 @@ public boolean isMultiImport() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ + @Override public int getChildCount() { int result = 0; - if (reference != null) result++; + result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { - if (reference != null) { - if (index == 0) return reference; - } + if (index == 0) return reference; throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (reference instanceof TypeReference) ? 1 : 0; } @@ -137,51 +141,59 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (reference instanceof TypeReference && index == 0) { - return (TypeReference)reference; + return (TypeReference) reference; } throw new ArrayIndexOutOfBoundsException(); } /** - * Returns the type reference of this import, if there is one. - * @return the reference of this import statement. - */ + * Returns the type reference of this import, if there is one. + * + * @return the reference of this import statement. + */ public TypeReference getTypeReference() { - return (reference instanceof TypeReference) - ? (TypeReference)reference : null; + return (reference instanceof TypeReference) + ? (TypeReference) reference : null; } /** - * Returns the package reference of this import, if there is one. - * @return the reference of this import statement. - */ - + * Returns the package reference of this import, if there is one. + * + * @return the reference of this import statement. + */ + @Override public PackageReference getPackageReference() { - return (reference instanceof PackageReference) ? - (PackageReference)reference : null; + return (reference instanceof PackageReference) ? + (PackageReference) reference : null; } /** - * Returns the reference of this import, either a - * type or a package reference. - * @return the reference of this import statement. - */ - + * Returns the reference of this import, either a + * type or a package reference. + * + * @return the reference of this import statement. + */ + @Nonnull public TypeReferenceInfix getReference() { return reference; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnImport(this); + v.performActionOnImport(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printImport(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaNonTerminalProgramElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaNonTerminalProgramElement.java index 9267b3d984d..0b3e50173d6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaNonTerminalProgramElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaNonTerminalProgramElement.java @@ -13,110 +13,113 @@ package de.uka.ilkd.key.java; +import de.uka.ilkd.key.rule.MatchConditions; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.rule.MatchConditions; -import de.uka.ilkd.key.util.Debug; +import java.util.List; /** - * Top level implementation of a Java {@link NonTerminalProgramElement}. + * Top level implementation of a Java {@link NonTerminalProgramElement}. * taken from COMPOST and changed to achieve an immutable structure */ -public abstract class JavaNonTerminalProgramElement - extends JavaProgramElement - implements NonTerminalProgramElement { - - public JavaNonTerminalProgramElement() { - } +public abstract class JavaNonTerminalProgramElement + extends JavaProgramElement + implements NonTerminalProgramElement { - /** * Java program element. + * * @param list as ExtList with children of the node */ + @Deprecated public JavaNonTerminalProgramElement(ExtList list) { super(list); } - + @Deprecated + public JavaNonTerminalProgramElement(ExtList children, PositionInfo pos) { + super(children, pos); + } + + public JavaNonTerminalProgramElement(List comments) { + super(comments); + } + + public JavaNonTerminalProgramElement(PositionInfo pi, List comments) { + super(pi, comments); + } + public JavaNonTerminalProgramElement(PositionInfo pos) { super(pos); } - - public JavaNonTerminalProgramElement(ExtList children, PositionInfo pos) { - super(children, pos); - } - - + /** * returns the index of element el in array arr + * * @param arr the array where the element is looked for - * @param el the element to look for + * @param el the element to look for * @return the index of the element (-1 if not found) */ protected int getArrayPos(ImmutableArray arr, ProgramElement el) { - for (int i = 0, sz = arr.size() ;i= max; } - - + + /** * matches successively all children of this current node. Thereby the * offset-th child is matched against source.getSource(). The call * source.next has to be done in the @link ProgramElement#match method - * of the currently matched child in case of a successful match. This is - * not done here (rationale: schemavariables matching on lists can be + * of the currently matched child in case of a successful match. This is + * not done here (rationale: schemavariables matching on lists can be * implemented easy). - * - * - * @param source the SourceData with the children to be matched + * + * @param source the SourceData with the children to be matched * @param matchCond the MatchConditions found so far - * @param offset the int denoting the index of the child to start with - * @return the resulting match conditions or null if matching failed + * @param offset the int denoting the index of the child to start with + * @return the resulting match conditions or null if matching failed */ - protected MatchConditions matchChildren(SourceData source, - MatchConditions matchCond, int offset) { - - for (int i = offset, sz = getChildCount(); i comments; - private final Comment[] comments; - private int hashCode = -1; public JavaProgramElement() { - comments = NO_COMMENTS; + this((List) null); + } + + public JavaProgramElement(@Nullable List comments) { + this(null, comments); + } + + public JavaProgramElement(@Nullable PositionInfo pi, @Nullable List comments) { + super(pi); + this.comments = comments == null ? Collections.emptyList() : Collections.unmodifiableList(comments); } - /** - * Java program element. + * Java program element. + * * @param list ExtList with comments */ public JavaProgramElement(ExtList list) { super(list); comments = extractComments(list); } - + /** * creates a java program element with the given position information - * @param pos the PositionInfo where the Java program element occurs in - * the source + * + * @param pos the PositionInfo where the Java program element occurs in + * the source */ public JavaProgramElement(PositionInfo pos) { - super(pos); - comments = NO_COMMENTS; + super(pos); + comments = Collections.emptyList(); } - + public JavaProgramElement(ExtList children, PositionInfo pos) { super(children, pos); comments = extractComments(children); } - + /** * collects comments contained in the given list + * * @param list the ExtList with children and comments of this node */ - private Comment[] extractComments(ExtList list) { - final Comment[] c = list.collect(Comment.class); - return c == null ? NO_COMMENTS : c; + private static List extractComments(ExtList list) { + var c = list.collectList(Comment.class); + return c == null ? Collections.emptyList() : c; } - /** - * Get comments. - * @return the comments. + * Get comments. + * + * @return the comments. */ - @Override + @Override public Comment[] getComments() { - return comments; + return comments.toArray(new Comment[0]); } - - @Override + @Override public void prettyPrint(PrettyPrinter w) throws IOException { - int s = (comments != null) ? comments.length : 0; + int s = (comments != null) ? comments.size() : 0; int t = 0; for (int i = 0; i < s; i += 1) { - Comment c = comments[i]; + Comment c = comments.get(i); if (c.isPrefixed()) { c.prettyPrint(w); } else { @@ -106,10 +113,10 @@ public void prettyPrint(PrettyPrinter w) throws IOException { prettyPrintMain(w); if (t > 0) { for (int i = 0; i < s; i += 1) { - Comment c = comments[i]; + Comment c = comments.get(i); if (!c.isPrefixed()) { if (c instanceof SingleLineComment) { - w.scheduleComment((SingleLineComment)c); + w.scheduleComment((SingleLineComment) c); } else { c.prettyPrint(w); } @@ -118,25 +125,26 @@ public void prettyPrint(PrettyPrinter w) throws IOException { } } - + /** - * Prints main content of current node and all syntactical children. - * Hook method of prettyPrint; defaults to do nothing. + * Prints main content of current node and all syntactical children. + * Hook method of prettyPrint; defaults to do nothing. */ - protected void prettyPrintMain(PrettyPrinter w) throws IOException {} - + protected void prettyPrintMain(PrettyPrinter w) throws IOException { + //empty + } - /** commented in interface SourceElement. The default equals - * method compares two elements by testing if they have the + /** + * commented in interface SourceElement. The default equals + * method compares two elements by testing if they have the * same type and calling the default equals method. */ - @Override - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { - return (this.getClass() == se.getClass()); + @Override + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { + return (this.getClass() == se.getClass()); } - + protected int computeHashCode() { int result = 17 * this.getClass().hashCode(); return result; @@ -158,48 +166,52 @@ public final int hashCode() { return hashCode; } - @Override - public boolean equals(Object o){ - if(o == this) { - return true; - } - if ( o == null || o.getClass() != this.getClass() ) { - return false; - } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o == null || o.getClass() != this.getClass()) { + return false; + } - return equalsModRenaming((JavaProgramElement)o, - NameAbstractionTableDisabled.INSTANCE); + return equalsModRenaming((JavaProgramElement) o, + NameAbstractionTableDisabled.INSTANCE); } - - /** this is the default implementation of the signature, which is - * used to determine program similarity. + + /** + * this is the default implementation of the signature, which is + * used to determine program similarity. + * * @param ec TODO */ public String reuseSignature(Services services, ExecutionContext ec) { - final String s = getClass().toString(); - return s.substring(s.lastIndexOf('.')+1, s.length()); + final String s = getClass().toString(); + return s.substring(s.lastIndexOf('.') + 1); } - - - /** this class is used by method call. As in this case we do not + + + /** + * this class is used by method call. As in this case we do not * want to abstract from names */ static class NameAbstractionTableDisabled extends NameAbstractionTable { - - - public static final NameAbstractionTableDisabled INSTANCE = new NameAbstractionTableDisabled(); - - public void add(SourceElement pe1, SourceElement pe2) {} - public boolean sameAbstractName(SourceElement pe1, - SourceElement pe2) { - return pe1.equals ( pe2 ); - } + + public static final NameAbstractionTableDisabled INSTANCE = new NameAbstractionTableDisabled(); + + public void add(SourceElement pe1, SourceElement pe2) { + } + + public boolean sameAbstractName(SourceElement pe1, + SourceElement pe2) { + return pe1.equals(pe2); + } } - - @Override + + @Override public MatchConditions match(SourceData source, MatchConditions matchCond) { final ProgramElement src = source.getSource(); LOGGER.debug("Program match start (template {}, source {})", this, src); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaSourceElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaSourceElement.java index f441d3b106a..fccc5da768c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaSourceElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaSourceElement.java @@ -13,174 +13,170 @@ package de.uka.ilkd.key.java; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URI; - import org.key_project.util.ExtList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.StringWriter; +import java.net.URI; +import java.util.Objects; + /** - * Top level implementation of a Java {@link SourceElement}. - * taken from COMPOST and changed to achieve an immutable structure + * Top level implementation of a Java {@link SourceElement}. + *

+ * This class is intended to be immutable. */ public abstract class JavaSourceElement implements SourceElement { private static final Logger LOGGER = LoggerFactory.getLogger(JavaSourceElement.class); + @Nonnull private final PositionInfo posInfo; - /** - * Java source element. - */ public JavaSourceElement() { - posInfo=PositionInfo.UNDEFINED; + posInfo = PositionInfo.UNDEFINED; } - - /** - * Java source element. - * @param pi PositionInfo the PositionInfo of the element - */ - public JavaSourceElement(PositionInfo pi) { - posInfo=getPosInfo(pi); - } /** - * Java source element. - * @param children a list of the children of this element. May contain: - * PositionInfo + * @param pi PositionInfo the PositionInfo of the element + */ + public JavaSourceElement(@Nullable PositionInfo pi) { + posInfo = getPosInfo(pi); + } + + /** + * @param children a list of the children of this element. May contain: + * PositionInfo */ + @Deprecated public JavaSourceElement(ExtList children) { - posInfo = getPosInfo(children.get(PositionInfo.class)); + posInfo = getPosInfo(children.get(PositionInfo.class)); } + @Deprecated public JavaSourceElement(ExtList children, PositionInfo pos) { posInfo = getPosInfo(pos); } /** - * internal method use to guarantee the position info object is + * Internal method use to guarantee the position info object is * always not the null reference - * @param p a PositionInfo - * @return if p is null the undefined - * position ({@link PositionInfo#UNDEFINED}) is returned otherwise - * p + * + * @param p a PositionInfo + * @return if {@code p} is {@code null} the undefined + * position ({@link PositionInfo#UNDEFINED}) is returned otherwise + * {@code p} */ - private PositionInfo getPosInfo(PositionInfo p) { - final PositionInfo pos; - if (p==null) { - pos = PositionInfo.UNDEFINED; - } else { - pos = p; - } - return pos; - } - + @Nonnull + private static PositionInfo getPosInfo(PositionInfo p) { + return Objects.requireNonNullElse(p, PositionInfo.UNDEFINED); + } /** - * Finds the source element that occurs first in the source. The default - * implementation returns this element, which is correct for all terminal - * program elements, and many non terminals such as statements and prefixed - * operators. - * @return the first source element in the syntactical representation of - * this element, may be equals to this element. - * @see #toSource() - * @see #getStartPosition() + * Finds the source element that occurs first in the source. The default + * implementation returns this element, which is correct for all terminal + * program elements, and many non terminals such as statements and prefixed + * operators. + * + * @return the first source element in the syntactical representation of + * this element, may be equals to this element. + * @see #toSource() + * @see #getStartPosition() */ - + @Nonnull public SourceElement getFirstElement() { return this; } @Override public SourceElement getFirstElementIncludingBlocks() { - return getFirstElement(); + return getFirstElement(); } /** - * Finds the source element that occurs last in the source. The - * default implementation returns this element, which is correct - * for all terminal program elements, and many non terminals such - * as statements and prefixed operators. - * @return the last source element in the syntactical representation of - * this element, may be equals to this element. - * @see #toSource() - * @see #getEndPosition() + * Finds the source element that occurs last in the source. The + * default implementation returns this element, which is correct + * for all terminal program elements, and many non terminals such + * as statements and prefixed operators. + * + * @return the last source element in the syntactical representation of + * this element, may be equals to this element. + * @see #toSource() + * @see #getEndPosition() */ - + @Nonnull public SourceElement getLastElement() { return this; } - /** - * Pretty printing the source element. + * Creates a syntactical representation of the source element using + * the {@link #prettyPrint} method. */ - - public abstract void prettyPrint(PrettyPrinter w) throws IOException; - - /** - * Creates a syntactical representation of the source element using - * the {@link #prettyPrint} method. - */ - public String toSource() { return toString(); } - /** - Returns the start position of the primary token of this element. - To get the start position of the syntactical first token, - call the corresponding method of getFirstElement(). - @return the start position of the primary token. + /** + * Returns the start position of the primary token of this element. + * To get the start position of the syntactical first token, + * call the corresponding method of getFirstElement(). + * + * @return the start position of the primary token. */ - public Position getStartPosition(){ - return posInfo.getStartPosition(); + @Nonnull + public Position getStartPosition() { + return posInfo.getStartPosition(); } /** - Returns the end position of the primary token of this element. - To get the end position of the syntactical first token, - call the corresponding method of getLastElement(). - @return the end position of the primary token. + * Returns the end position of the primary token of this element. + * To get the end position of the syntactical first token, + * call the corresponding method of getLastElement(). + * + * @return the end position of the primary token. */ - public Position getEndPosition(){ - return posInfo.getEndPosition(); + public Position getEndPosition() { + return posInfo.getEndPosition(); } /** - Returns the relative position (number of blank heading lines and - columns) of the primary token of this element. - To get the relative position of the syntactical first token, - call the corresponding method of getFirstElement(). - @return the relative position of the primary token. + * Returns the relative position (number of blank heading lines and + * columns) of the primary token of this element. + * To get the relative position of the syntactical first token, + * call the corresponding method of getFirstElement(). + * + * @return the relative position of the primary token. */ - public Position getRelativePosition(){ - return posInfo.getRelativePosition(); + public Position getRelativePosition() { + return posInfo.getRelativePosition(); } - + public PositionInfo getPositionInfo() { return posInfo; } - - /** toString */ + /** + * toString + */ public String toString() { - StringWriter sw=new StringWriter(); - PrettyPrinter pp=new PrettyPrinter(sw, true); - return toString(pp,sw); + StringWriter sw = new StringWriter(); + PrettyPrinter pp = new PrettyPrinter(sw, true); + return toString(pp, sw); } - + /*Sometimes CompilableJavaPP must be given as argument instead of the ordinary PrettyPrinter */ - public String toString(PrettyPrinter pp, StringWriter sw){ + public String toString(PrettyPrinter pp, StringWriter sw) { try { pp.setIndentationLevel(0); prettyPrint(pp); @@ -188,21 +184,25 @@ public String toString(PrettyPrinter pp, StringWriter sw){ LOGGER.error("Pretty printing of JavaSourceElement failed", e); } String r = sw.toString(); - r = r.replace('\n',' '); - r = r.replace('\t',' '); + r = r.replace('\n', ' '); + r = r.replace('\t', ' '); return r; } - - /** this violates immutability, but the method is only called - * right after the object is created... - * @param s the path of the parent class as String - */ + + /** + * this violates immutability, but the method is only called + * right after the object is created... + * + * @param s the path of the parent class as String + */ protected void setParentClass(URI s) { posInfo.setParentClassURI(s); } - - /** get the class the statement originates from */ + + /** + * get the class the statement originates from + */ public String getParentClass() { return posInfo.getParentClass(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/NonTerminalProgramElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/NonTerminalProgramElement.java index 362209943b1..95f58176d84 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/NonTerminalProgramElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/NonTerminalProgramElement.java @@ -14,26 +14,28 @@ package de.uka.ilkd.key.java; /** - * Non terminal program element. + * Non terminal program element. * taken from COMPOST and changed to achieve an immutable structure */ public interface NonTerminalProgramElement extends ProgramElement { - /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + /** + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ int getChildCount(); - /** - * Returns the child at the specified index in this node's "virtual" - * child array. - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + /** + * Returns the child at the specified index in this node's "virtual" + * child array. + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ ProgramElement getChildAt(int index); - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java index 9420001c886..3a5152acae0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/PackageSpecification.java @@ -13,85 +13,104 @@ package de.uka.ilkd.key.java; -import org.key_project.util.ExtList; - import de.uka.ilkd.key.java.reference.PackageReference; import de.uka.ilkd.key.java.reference.PackageReferenceContainer; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Package specification. + * Package specification. * taken from COMPOST and changed to achieve an immutable structure */ -public class PackageSpecification extends JavaNonTerminalProgramElement implements PackageReferenceContainer { +public final class PackageSpecification extends JavaNonTerminalProgramElement implements PackageReferenceContainer { /** - * Reference. + * Reference. */ - protected final PackageReference reference; + @Nonnull + private final PackageReference reference; + + public PackageSpecification(PositionInfo pi, List comments, @Nonnull PackageReference reference) { + super(pi, comments); + this.reference = reference; + } /** * Package specification. + * * @param children an ExtList with children */ public PackageSpecification(ExtList children) { super(children); - reference=children.get(PackageReference.class); + reference = children.get(PackageReference.class); } public PackageSpecification(PackageReference reference) { - this.reference = reference; + this(null, null, reference); } + @Override + @Nonnull public SourceElement getLastElement() { return reference; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ + @Override public int getChildCount() { int result = 0; - if (reference != null) result++; + result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ + @Override public ProgramElement getChildAt(int index) { - if (reference != null) { - if (index == 0) return reference; - } + if (index == 0) return reference; throw new ArrayIndexOutOfBoundsException(); } /** - * Get package reference. - * @return the package reference. + * Get package reference. + * + * @return the package reference. */ + @Override public PackageReference getPackageReference() { return reference; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnPackageSpecification(this); + v.performActionOnPackageSpecification(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printPackageSpecification(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/PositionInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/PositionInfo.java index 830d67d5a71..b2597bb5d83 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/PositionInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/PositionInfo.java @@ -13,31 +13,43 @@ package de.uka.ilkd.key.java; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.net.URI; import java.nio.file.Paths; /** - * represents a group of three Positions: relativePosition, - * startPosition, endPosition - * + * This class represents a group of three positions: the relative, start and end position. + *

* 2019-09-10 Wolfram Pfeifer: work with URIs instead of Strings -> more robust, more general */ public class PositionInfo { - /** Unknown URI (enables us to always have a non-null value for fileURI) */ + /** + * Unknown URI (enables us to always have a non-null value for fileURI) + */ public static final URI UNKNOWN_URI = URI.create("UNKNOWN://unknown"); - /** PositionInfo with undefined positions. */ + /** + * PositionInfo with undefined positions. + */ public static final PositionInfo UNDEFINED = new PositionInfo(); /** * TODO: What is the purpose of this? To which position is this one relative? */ + @Nonnull private final Position relPos; - /** The start position. */ + /** + * The start position. + */ + @Nonnull private final Position startPos; - /** The end position. */ + /** + * The end position. + */ + @Nonnull private final Position endPos; /** @@ -61,11 +73,12 @@ private PositionInfo() { /** * Creates a new PositionInfo without resource information but only with positions. - * @param relPos the relative position + * + * @param relPos the relative position * @param startPos the start position - * @param endPos the end position + * @param endPos the end position */ - public PositionInfo(Position relPos, Position startPos, Position endPos) { + public PositionInfo(@Nonnull Position relPos, @Nonnull Position startPos, @Nonnull Position endPos) { this.relPos = relPos; this.startPos = startPos; this.endPos = endPos; @@ -74,12 +87,14 @@ public PositionInfo(Position relPos, Position startPos, Position endPos) { /** * Creates a new PositionInfo without the given resource information. - * @param relPos the relative position + * + * @param relPos the relative position * @param startPos the start position - * @param endPos the end position - * @param fileURI the resource the PositionInfo refers to + * @param endPos the end position + * @param fileURI the resource the PositionInfo refers to */ - public PositionInfo(Position relPos, Position startPos, Position endPos, URI fileURI) { + public PositionInfo(@Nonnull Position relPos, @Nonnull Position startPos, @Nonnull Position endPos, + @Nullable URI fileURI) { this.relPos = relPos; this.startPos = startPos; this.endPos = endPos; @@ -90,8 +105,10 @@ public PositionInfo(Position relPos, Position startPos, Position endPos, URI fil } } - /** this violates immutability, but the method is only called + /** + * this violates immutability, but the method is only called * right after the object is created... + * * @param parent the parent class of this PositionInfo */ void setParentClassURI(URI parent) { @@ -101,9 +118,10 @@ void setParentClassURI(URI parent) { /** * Returns the path of the parent file the PositionInfo refers to * (the class the statement originates from). - * @deprecated This method should no longer be used, as PositionInfo can now be used with - * resources other than files. Use {@link #getParentClassURI()} instead. + * * @return the filename as a string if parentClass uses the "file" protocol or null otherwise + * @deprecated This method should no longer be used, as PositionInfo can now be used with + * resources other than files. Use {@link #getParentClassURI()} instead. */ @Deprecated // only kept for compatibility reasons public String getParentClass() { @@ -115,9 +133,10 @@ public String getParentClass() { /** * Returns the path of the file the PositionInfo refers to. + * + * @return the filename as a string if fileURI uses the "file" protocol or null otherwise * @deprecated This method should no longer be used, as PositionInfo can now be used with * resources other than files. Use {@link #getURI()} instead. - * @return the filename as a string if fileURI uses the "file" protocol or null otherwise */ @Deprecated // only kept for compatibility reasons public String getFileName() { @@ -150,6 +169,7 @@ public Position getEndPosition() { /** * Creates a new PositionInfo from joining the intervals of the given PositionInfos. * The file informations have to match, otherwise null is returned. + * * @param p1 the first PositionInfo * @param p2 the second PositionInfo * @return a new PositionInfo starting at the minimum of the two start positions and @@ -175,7 +195,7 @@ public static PositionInfo join(PositionInfo p1, PositionInfo p2) { Position start; Position end; if (p1.startPos != Position.UNDEFINED && !p1.startPos.isNegative() - && p1.startPos.compareTo(p2.startPos) < 0) { + && p1.startPos.compareTo(p2.startPos) < 0) { start = p1.startPos; } else { start = p2.startPos; @@ -192,6 +212,7 @@ public static PositionInfo join(PositionInfo p1, PositionInfo p2) { /** * Checks if start and end position are both defined and in valid range. + * * @return true iff start and end are valid */ public boolean startEndValid() { @@ -205,7 +226,7 @@ public String toString() { return "UNDEFINED"; } else { return ((fileURI == UNKNOWN_URI ? "" : fileURI) + " rel. Pos: " + relPos - + " start Pos: " + startPos + " end Pos: " + endPos); + + " start Pos: " + startPos + " end Pos: " + endPos); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementBlock.java index 254a0efbf7b..a95bf19ee27 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementBlock.java @@ -13,11 +13,6 @@ package de.uka.ilkd.key.java; -import java.util.ArrayList; - -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - import de.uka.ilkd.key.java.declaration.TypeDeclaration; import de.uka.ilkd.key.java.declaration.TypeDeclarationContainer; import de.uka.ilkd.key.java.statement.JavaStatement; @@ -26,49 +21,64 @@ import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramPrefix; import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; /** - * Statement block. + * Statement block. * taken from COMPOST and changed to achieve an immutable structure */ public class StatementBlock extends JavaStatement - implements StatementContainer, TypeDeclarationContainer, - VariableScope, TypeScope, ProgramPrefix { - + implements StatementContainer, TypeDeclarationContainer, + VariableScope, TypeScope, ProgramPrefix { + /** - * Body. + * Body. */ + @Nonnull private final ImmutableArray body; - - private final int prefixLength; - - private final MethodFrame innerMostMethodFrame; - - + + private final int prefixLength; + + @Nullable + private final MethodFrame innerMostMethodFrame; + + public StatementBlock(PositionInfo pi, List comments, + @Nonnull ImmutableArray body, + int prefixLength, MethodFrame innerMostMethodFrame) { + super(pi, comments); + this.body = body; + this.prefixLength = prefixLength; + this.innerMostMethodFrame = innerMostMethodFrame; + } + public StatementBlock() { - body = new ImmutableArray(); - prefixLength = 1; - innerMostMethodFrame = null; + this(null, null, new ImmutableArray<>(), 1, null); } - + /** - * Statement block. - * @param children an ExtList that contains the children + * Statement block. + * + * @param children an ExtList that contains the children */ public StatementBlock(ExtList children) { super(children); - body = new - ImmutableArray(children.collect(Statement.class)); - - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + body = new ImmutableArray<>(children.collect(Statement.class)); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); } - public StatementBlock(ImmutableArray as) { + public StatementBlock(@Nonnull ImmutableArray as) { + super((PositionInfo) null, null); // check for non-null elements (bug fix) Debug.assertDeepNonNull(as, "statement block contructor"); body = as; @@ -79,54 +89,58 @@ public StatementBlock(ImmutableArray as) { public StatementBlock(Statement as) { - this(new ImmutableArray(as)); + this(new ImmutableArray<>(as)); } public StatementBlock(Statement... body) { - this(new ImmutableArray(body)); + this(new ImmutableArray<>(body)); } @Override public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { - return super.equalsModRenaming(se, nat) - && (this.getStartPosition().equals(Position.UNDEFINED) || // why do we care here about position info and nowhere else? - se.getStartPosition().equals(Position.UNDEFINED) || - this.getStartPosition().getLine() == se.getStartPosition().getLine()); + return super.equalsModRenaming(se, nat) + // why do we care here about position info and nowhere else? + && (this.getStartPosition().equals(Position.UNDEFINED) || + se.getStartPosition().equals(Position.UNDEFINED) || + this.getStartPosition().getLine() == se.getStartPosition().getLine()); } - /** computes the prefix elements for the given array of statment block */ + /** + * computes the prefix elements for the given array of statment block + */ public static ImmutableArray computePrefixElements(ImmutableArray b, - ProgramPrefix current) { + ProgramPrefix current) { final ArrayList prefix = new ArrayList<>(); prefix.add(current); - + while (current.hasNextPrefixElement()) { current = current.getNextPrefixElement(); prefix.add(current); } - - return new ImmutableArray(prefix); - } + return new ImmutableArray<>(prefix); + } /** - * Get body. - * @return the statement array wrapper. + * Get body. + * + * @return the statement array wrapper. */ - + @Nonnull public ImmutableArray getBody() { return body; } public final boolean isEmpty() { - return body.isEmpty(); + return body.isEmpty(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { @@ -134,24 +148,23 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (body != null) { - return body.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return body.get(index); } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { @@ -168,24 +181,20 @@ public int getStatementCount() { */ public Statement getStatementAt(int index) { - if (body != null) { - return body.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return body.get(index); } /** - * Get the number of type declarations in this container. - * @return the number of type declarations. + * Get the number of type declarations in this container. + * + * @return the number of type declarations. */ public int getTypeDeclarationCount() { int count = 0; - if (body != null) { - for (int i = body.size() - 1; i >= 0; i -= 1) { - if (body.get(i) instanceof TypeDeclaration) { - count += 1; - } + for (int i = body.size() - 1; i >= 0; i -= 1) { + if (body.get(i) instanceof TypeDeclaration) { + count += 1; } } return count; @@ -201,27 +210,27 @@ public int getTypeDeclarationCount() { */ public TypeDeclaration getTypeDeclarationAt(int index) { - if (body != null) { - int s = body.size(); - for (int i = 0; i < s && index >= 0; i++) { - Statement st = body.get(i); - if (st instanceof TypeDeclaration) { - if (index == 0) { - return (TypeDeclaration)st; - } - index -= 1; + int s = body.size(); + for (int i = 0; i < s && index >= 0; i++) { + Statement st = body.get(i); + if (st instanceof TypeDeclaration) { + if (index == 0) { + return (TypeDeclaration) st; } + index -= 1; } } throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnStatementBlock(this); + v.performActionOnStatementBlock(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -229,6 +238,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } + @Nonnull public SourceElement getFirstElement() { if (isEmpty()) return this; final SourceElement e = getBody().get(0); @@ -237,11 +247,11 @@ public SourceElement getFirstElement() { @Override public SourceElement getFirstElementIncludingBlocks() { - if (isEmpty()) return this; - else return getBody().get(0); + if (isEmpty()) return this; + else return getBody().get(0); } - + @Override public boolean hasNextPrefixElement() { return body.size() != 0 && (body.get(0) instanceof ProgramPrefix); @@ -255,12 +265,12 @@ public ProgramPrefix getNextPrefixElement() { throw new IndexOutOfBoundsException("No next prefix element " + this); } } - + @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() ? ((ProgramPrefix)body.get(0)).getLastPrefixElement() : this; + return hasNextPrefixElement() ? ((ProgramPrefix) body.get(0)).getLastPrefixElement() : this; } - + @Override public int getPrefixLength() { return prefixLength; @@ -270,10 +280,10 @@ public int getPrefixLength() { public MethodFrame getInnerMostMethodFrame() { return innerMostMethodFrame; } - + @Override public ImmutableArray getPrefixElements() { - return computePrefixElements(body,this); + return computePrefixElements(body, this); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassInitializer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassInitializer.java index d7696f3826a..142b46d0734 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassInitializer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassInitializer.java @@ -24,6 +24,7 @@ import de.uka.ilkd.key.java.declaration.modifier.Static; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; public class ClassInitializer extends JavaDeclaration implements MemberDeclaration, StatementContainer { @@ -161,6 +162,7 @@ public boolean isStatic() { return modArray != null && modArray.size()!=0; } + @Nonnull public SourceElement getLastElement() { return body; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ConstructorDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ConstructorDeclaration.java index df0d3f2fb84..ec55d7c179a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ConstructorDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ConstructorDeclaration.java @@ -13,71 +13,82 @@ package de.uka.ilkd.key.java.declaration; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.StatementBlock; import de.uka.ilkd.key.java.abstraction.Constructor; +import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * The getTypeReference method returns null - constructors do not have - * explicite return types. A constructor declaration contains its own - * name even though it must match the class name: the name occurs as - * syntactical element and hence must be represented. - * taken from COMPOST and changed to achieve an immutable structure + * The getTypeReference method returns null - constructors do not have + * explicite return types. A constructor declaration contains its own + * name even though it must match the class name: the name occurs as + * syntactical element and hence must be represented. + * taken from COMPOST and changed to achieve an immutable structure */ public class ConstructorDeclaration extends MethodDeclaration implements Constructor { + public ConstructorDeclaration(PositionInfo pi, List comments, @Nonnull ImmutableArray modArray, TypeReference returnType, Comment[] voidComments, ProgramElementName name, ImmutableArray parameters, Throws exceptions, StatementBlock body, boolean parentIsInterfaceDeclaration) { + super(pi, comments, modArray, returnType, voidComments, name, parameters, exceptions, body, parentIsInterfaceDeclaration); + } /** * Constructor declaration. - * @parm children an ExtList with the children. May - * include: - * a TypeReference (as a reference to the return type), - * a de.uka.ilkd.key.logic.ProgramElementName (as Name of the - * method), - * several ParameterDeclaration (as parameters of the declared - * method), - * a StatementBlock (as body of the declared method), - * several Modifier (taken as modifiers of the declaration), - * a Comment + * * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * parent is an InterfaceDeclaration + * @parm children an ExtList with the children. May + * include: + * a TypeReference (as a reference to the return type), + * a de.uka.ilkd.key.logic.ProgramElementName (as Name of the + * method), + * several ParameterDeclaration (as parameters of the declared + * method), + * a StatementBlock (as body of the declared method), + * several Modifier (taken as modifiers of the declaration), + * a Comment */ public ConstructorDeclaration(ExtList children, - boolean parentIsInterfaceDeclaration) { - super(children, parentIsInterfaceDeclaration, null); + boolean parentIsInterfaceDeclaration) { + super(children, parentIsInterfaceDeclaration, null); } - + /** * Constructor declaration. - * @param modifiers a modifier array. - * @param name an identifier. - * @param parameters a parameter declaration mutable list. - * @param exceptions a throws. - * @param body a statement block. + * + * @param modifiers a modifier array. + * @param name an identifier. + * @param parameters a parameter declaration mutable list. + * @param exceptions a throws. + * @param body a statement block. * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * parent is an InterfaceDeclaration */ @Deprecated - public ConstructorDeclaration(Modifier[] modifiers, - ProgramElementName name, - ParameterDeclaration[] parameters, - Throws exceptions, - StatementBlock body, - boolean parentIsInterfaceDeclaration) { - super(modifiers, - null, - name, - parameters, - exceptions, - body, - parentIsInterfaceDeclaration); + public ConstructorDeclaration(Modifier[] modifiers, + ProgramElementName name, + ParameterDeclaration[] parameters, + Throws exceptions, + StatementBlock body, + boolean parentIsInterfaceDeclaration) { + super(modifiers, + null, + name, + parameters, + exceptions, + body, + parentIsInterfaceDeclaration); } - + /** * Constructors are never abstract. */ @@ -86,7 +97,7 @@ public boolean isAbstract() { return false; } - + /** * Constructors are never final. */ @@ -95,7 +106,7 @@ public boolean isFinal() { return false; } - + /** * Constructors are never native. */ @@ -104,7 +115,7 @@ public boolean isNative() { return false; } - + /** * Constructors are never static. */ @@ -113,7 +124,7 @@ public boolean isStatic() { return false; } - + /** * Constructors are never strictfp. */ @@ -122,7 +133,7 @@ public boolean isStrictFp() { return false; } - + /** * Constructors are never synchronized. */ @@ -132,8 +143,8 @@ public boolean isSynchronized() { } - @Override + @Override public void visit(Visitor v) { - v.performActionOnConstructorDeclaration(this); + v.performActionOnConstructorDeclaration(this); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldDeclaration.java index b26abe58a78..ea2bea01849 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldDeclaration.java @@ -13,61 +13,67 @@ package de.uka.ilkd.key.java.declaration; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Field declaration. + * Field declaration. * taken from COMPOST and changed to achieve an immutable structure */ -public class FieldDeclaration extends VariableDeclaration implements MemberDeclaration { +public final class FieldDeclaration extends VariableDeclaration implements MemberDeclaration { + private final ImmutableArray fieldSpecs; + public FieldDeclaration(PositionInfo pi, List comments, @Nonnull ImmutableArray modArray, + TypeReference typeReference, boolean parentIsInterfaceDeclaration, + ImmutableArray fieldSpecs) { + super(pi, comments, modArray, typeReference, parentIsInterfaceDeclaration); + this.fieldSpecs = fieldSpecs; + } /** - * Field specs. - */ - - protected final ImmutableArray fieldSpecs; - - /** - * Field declaration. - * @param mods a modifier mutable list. - * @param typeRef a type reference. - * @param vars a variable specification array. - * @param parentIsInterfaceDeclaration a boolean set true - * iff parent is an InterfaceDeclaration + * Field declaration. + * + * @param mods a modifier mutable list. + * @param typeRef a type reference. + * @param vars a variable specification array. + * @param parentIsInterfaceDeclaration a boolean set true + * iff parent is an InterfaceDeclaration */ public FieldDeclaration(Modifier[] mods, TypeReference typeRef, - FieldSpecification[] vars, - boolean parentIsInterfaceDeclaration) { - super(mods,typeRef,parentIsInterfaceDeclaration); - fieldSpecs = new - ImmutableArray(vars); + FieldSpecification[] vars, + boolean parentIsInterfaceDeclaration) { + super(mods, typeRef, parentIsInterfaceDeclaration); + fieldSpecs = new ImmutableArray<>(vars); } /** - * Field declaration. - * @param children an ExtList of children. May include: - * several FieldSpecification (for the field) - * a TypeReference (as reference to the type of the declared variable) - * several Modifier (taken as modifiers of the declaration), - * a Comment - * @param parentIsInterfaceDeclaration a boolean set true + * Field declaration. + * + * @param children an ExtList of children. May include: + * several FieldSpecification (for the field) + * a TypeReference (as reference to the type of the declared variable) + * several Modifier (taken as modifiers of the declaration), + * a Comment + * @param parentIsInterfaceDeclaration a boolean set true */ - public FieldDeclaration(ExtList children, - boolean parentIsInterfaceDeclaration) { + public FieldDeclaration(ExtList children, + boolean parentIsInterfaceDeclaration) { super(children, parentIsInterfaceDeclaration); - fieldSpecs = new - ImmutableArray(children.collect(FieldSpecification.class)); + fieldSpecs = new + ImmutableArray<>(children.collect(FieldSpecification.class)); } - + public ImmutableArray getFieldSpecifications() { return fieldSpecs; } @@ -77,25 +83,27 @@ public ImmutableArray getVariables() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; - if (modArray != null) result += modArray.size(); + if (modArray != null) result += modArray.size(); if (typeReference != null) result++; - if (fieldSpecs != null) result += fieldSpecs.size(); + if (fieldSpecs != null) result += fieldSpecs.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -155,7 +163,7 @@ public boolean isPublic() { */ public boolean isStatic() { // return parentIsInterfaceDeclaration || super.isStatic(); - // DB 2012-05-08: interfaces may contain non-static model fields + // DB 2012-05-08: interfaces may contain non-static model fields return super.isStatic(); } @@ -174,7 +182,7 @@ public boolean isTransient() { public boolean isStrictFp() { return super.isStrictFp(); } - + /** * Test whether the declaration is model (the jml modifier is meant). */ @@ -191,12 +199,14 @@ public boolean isGhost() { return super.isGhost(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnFieldDeclaration(this); + v.performActionOnFieldDeclaration(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InheritanceSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InheritanceSpecification.java index 095fa2b33ea..3d293a65463 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InheritanceSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InheritanceSpecification.java @@ -13,70 +13,70 @@ package de.uka.ilkd.key.java.declaration; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.reference.TypeReference; +import de.uka.ilkd.key.java.reference.TypeReferenceContainer; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.reference.TypeReference; -import de.uka.ilkd.key.java.reference.TypeReferenceContainer; +import javax.annotation.Nonnull; +import java.util.List; /** - * Inheritance specification. - * @author AutoDoc + * Inheritance specification. + * + * @author AutoDoc */ public abstract class InheritanceSpecification - extends JavaNonTerminalProgramElement - implements TypeReferenceContainer { - - /** - * Supertypes. - */ + extends JavaNonTerminalProgramElement implements TypeReferenceContainer { protected final ImmutableArray supertypes; - - /** - * Inheritance specification. - */ + public InheritanceSpecification(PositionInfo pi, List comments, ImmutableArray supertypes) { + super(pi, comments); + this.supertypes = supertypes; + } public InheritanceSpecification() { - this.supertypes=null; + this(null, null, null); } /** - * Inheritance specification. - * @param supertype a type reference. + * Inheritance specification. + * + * @param supertype a type reference. */ public InheritanceSpecification(TypeReference supertype) { - this.supertypes = new ImmutableArray(supertype); + this(null, null, new ImmutableArray<>(supertype)); } /** - * Inheritance specification. - * @param supertypes a type reference mutable list. + * Inheritance specification. + * + * @param supertypes a type reference mutable list. */ public InheritanceSpecification(TypeReference[] supertypes) { - this.supertypes=new ImmutableArray(supertypes); + this(null, null, new ImmutableArray<>(supertypes)); } /** - * Inheritance specification. - * @param children the ExtList may include: a Comment - * several TypeReference (as references to the supertypes) - * a Comment + * Inheritance specification. + * + * @param children the ExtList may include: a Comment + * several TypeReference (as references to the supertypes) + * a Comment */ protected InheritanceSpecification(ExtList children) { super(children); - this.supertypes=new - ImmutableArray(children.collect(TypeReference.class)); + this.supertypes = new ImmutableArray<>(children.collect(TypeReference.class)); } + @Override + @Nonnull public SourceElement getLastElement() { if (supertypes == null) { return this; @@ -86,10 +86,12 @@ public SourceElement getLastElement() { /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ + @Override public int getChildCount() { int result = 0; if (supertypes != null) result += supertypes.size(); @@ -97,14 +99,16 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ + @Override public ProgramElement getChildAt(int index) { if (supertypes != null) { return supertypes.get(index); @@ -113,8 +117,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get supertypes. - * @return the type reference array wrapper. + * Get supertypes. + * + * @return the type reference array wrapper. */ public ImmutableArray getSupertypes() { @@ -122,10 +127,12 @@ public ImmutableArray getSupertypes() { } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (supertypes != null) ? supertypes.size() : 0; } @@ -139,6 +146,7 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (supertypes != null) { return supertypes.get(index); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/JavaDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/JavaDeclaration.java index 47b148bd70c..1dbf24b395b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/JavaDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/JavaDeclaration.java @@ -13,95 +13,90 @@ package de.uka.ilkd.key.java.declaration; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Declaration; +import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; +import de.uka.ilkd.key.java.PositionInfo; +import de.uka.ilkd.key.java.declaration.modifier.*; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Declaration; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.declaration.modifier.Abstract; -import de.uka.ilkd.key.java.declaration.modifier.Final; -import de.uka.ilkd.key.java.declaration.modifier.Ghost; -import de.uka.ilkd.key.java.declaration.modifier.Model; -import de.uka.ilkd.key.java.declaration.modifier.Native; -import de.uka.ilkd.key.java.declaration.modifier.NoState; -import de.uka.ilkd.key.java.declaration.modifier.Private; -import de.uka.ilkd.key.java.declaration.modifier.Protected; -import de.uka.ilkd.key.java.declaration.modifier.Public; -import de.uka.ilkd.key.java.declaration.modifier.Static; -import de.uka.ilkd.key.java.declaration.modifier.StrictFp; -import de.uka.ilkd.key.java.declaration.modifier.Synchronized; -import de.uka.ilkd.key.java.declaration.modifier.Transient; -import de.uka.ilkd.key.java.declaration.modifier.TwoState; -import de.uka.ilkd.key.java.declaration.modifier.VisibilityModifier; -import de.uka.ilkd.key.java.declaration.modifier.Volatile; +import javax.annotation.Nonnull; +import java.util.List; /** - * Java declaration. + * Java declaration. * taken from COMPOST and changed to achieve an immutable structure */ public abstract class JavaDeclaration extends JavaNonTerminalProgramElement - implements Declaration { + implements Declaration { /** * Modifiers. - * caches the wrapper for the modifiers. The wrapper is needed to get access - * to the array without hurting immutabilitiy */ + * + * Caches the wrapper for the modifiers. The wrapper is needed to get access + * to the array without hurting immutability. + */ + @Nonnull protected final ImmutableArray modArray; - + public JavaDeclaration(PositionInfo pi, List comments, @Nonnull ImmutableArray modArray) { + super(pi, comments); + this.modArray = modArray; + } + /** - * Java declaration. + * Java declaration. */ public JavaDeclaration() { - modArray = null; + this(null, null, new ImmutableArray<>()); } public JavaDeclaration(Modifier[] mods) { - modArray = new ImmutableArray(mods); + this(null, null, new ImmutableArray<>(mods)); } - + public JavaDeclaration(ImmutableArray mods) { - modArray = mods; + this(null, null, mods); } - + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. May - * include: several Modifier (taken as modifiers of the declaration), - * a Comment - */ + * include: several Modifier (taken as modifiers of the declaration), + * a Comment + */ public JavaDeclaration(ExtList children) { - super(children); - modArray = new ImmutableArray(children.collect(Modifier.class)); + super(children); + modArray = new ImmutableArray<>(children.collect(Modifier.class)); } /** - * Get modifiers. - * @return the modifier array wrapper. + * Get modifiers. + * + * @return the modifier array wrapper. */ public ImmutableArray getModifiers() { return modArray; } - + /** - * Returns a Public, Protected, or Private Modifier, if there - * is one, null otherwise. A return value of null can usually be - * interpreted as package visibility. + * Returns a Public, Protected, or Private Modifier, if there + * is one, null otherwise. A return value of null can usually be + * interpreted as package visibility. */ public VisibilityModifier getVisibilityModifier() { - if (modArray == null) { - return null; - } for (int i = modArray.size() - 1; i >= 0; i -= 1) { Modifier m = modArray.get(i); if (m instanceof VisibilityModifier) { - return (VisibilityModifier)m; + return (VisibilityModifier) m; } } return null; @@ -109,7 +104,7 @@ public VisibilityModifier getVisibilityModifier() { private boolean containsModifier(Class type) { - int s = (modArray == null) ? 0 : modArray.size(); + int s = modArray.size(); for (int i = 0; i < s; i += 1) { if (type.isInstance(modArray.get(i))) { return true; @@ -118,7 +113,7 @@ private boolean containsModifier(Class type) { return false; } - + /** * Test whether the declaration is abstract. */ @@ -126,7 +121,7 @@ protected boolean isAbstract() { return containsModifier(Abstract.class); } - + /** * Test whether the declaration is private. */ @@ -134,7 +129,7 @@ protected boolean isPrivate() { return containsModifier(Private.class); } - + /** * Test whether the declaration is protected. */ @@ -142,7 +137,7 @@ protected boolean isProtected() { return containsModifier(Protected.class); } - + /** * Test whether the declaration is public. */ @@ -150,7 +145,7 @@ protected boolean isPublic() { return containsModifier(Public.class); } - + /** * Test whether the declaration is static. */ @@ -158,7 +153,7 @@ protected boolean isStatic() { return containsModifier(Static.class); } - + /** * Test whether the declaration is transient. */ @@ -166,7 +161,7 @@ protected boolean isTransient() { return containsModifier(Transient.class); } - + /** * Test whether the declaration is model (the jml modifier is meant). */ @@ -178,11 +173,15 @@ protected boolean isModel() { * Get the state count of the declaration */ protected int getStateCount() { - if(containsModifier(TwoState.class)) { return 2; } - if(containsModifier(NoState.class)) { return 0; } + if (containsModifier(TwoState.class)) { + return 2; + } + if (containsModifier(NoState.class)) { + return 0; + } return 1; } - + /** * Test whether the declaration is ghost (the jml modifier is meant). */ @@ -190,7 +189,7 @@ protected boolean isGhost() { return containsModifier(Ghost.class); } - + /** * Test whether the declaration is volatile. */ @@ -198,7 +197,7 @@ protected boolean isVolatile() { return containsModifier(Volatile.class); } - + /** * Test whether the declaration is strictfp. */ @@ -206,7 +205,7 @@ protected boolean isStrictFp() { return containsModifier(StrictFp.class); } - + /** * Test whether the declaration is final. */ @@ -214,7 +213,7 @@ protected boolean isFinal() { return containsModifier(Final.class); } - + /** * Test whether the declaration is native. */ @@ -222,7 +221,7 @@ protected boolean isNative() { return containsModifier(Native.class); } - + /** * Test whether the declaration is synchronized. */ diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MethodDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MethodDeclaration.java index 57242a56d19..2efaa41644a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MethodDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MethodDeclaration.java @@ -13,35 +13,25 @@ package de.uka.ilkd.key.java.declaration; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Comment; -import de.uka.ilkd.key.java.NamedProgramElement; -import de.uka.ilkd.key.java.ParameterContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.VariableScope; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.Method; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Method declaration. + * Method declaration. * taken from COMPOST and changed to achieve an immutable structure */ public class MethodDeclaration extends JavaDeclaration - implements MemberDeclaration, - TypeReferenceContainer, - NamedProgramElement, - ParameterContainer, - Method, - VariableScope { + implements MemberDeclaration, TypeReferenceContainer, NamedProgramElement, ParameterContainer, Method, + VariableScope { protected final TypeReference returnType; protected final Comment[] voidComments; @@ -51,109 +41,129 @@ public class MethodDeclaration extends JavaDeclaration protected final StatementBlock body; - /** this field stores if parent is an InterfaceDeclaration because we will be + /** + * this field stores if parent is an InterfaceDeclaration because we will be * unable to walk the tree upwards to check this */ protected final boolean parentIsInterfaceDeclaration; + public MethodDeclaration(PositionInfo pi, List comments, @Nonnull ImmutableArray modArray, + TypeReference returnType, + Comment[] voidComments, ProgramElementName name, + ImmutableArray parameters, Throws exceptions, + StatementBlock body, boolean parentIsInterfaceDeclaration) { + super(pi, comments, modArray); + this.returnType = returnType; + this.voidComments = voidComments; + this.name = name; + this.parameters = parameters; + this.exceptions = exceptions; + this.body = body; + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; + } + /** - * Method declaration. - * @param children an ExtList of children. May - * include: a TypeReference (as a reference to the return type), a - * de.uka.ilkd.key.logic.ProgramElementName (as Name of the method), - * several ParameterDeclaration (as parameters of the declared method), a - * StatementBlock (as body of the declared method), several Modifier - * (taken as modifiers of the declaration), a Comment + * Method declaration. + * + * @param children an ExtList of children. May + * include: a TypeReference (as a reference to the return type), a + * de.uka.ilkd.key.logic.ProgramElementName (as Name of the method), + * several ParameterDeclaration (as parameters of the declared method), a + * StatementBlock (as body of the declared method), several Modifier + * (taken as modifiers of the declaration), a Comment * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * parent is an InterfaceDeclaration */ - public MethodDeclaration(ExtList children, - boolean parentIsInterfaceDeclaration, - Comment[] voidComments) { - super(children); - returnType = children.get(TypeReference.class); - this.voidComments = voidComments; - name = children.get(ProgramElementName.class); - this.parameters = new - ImmutableArray(children.collect(ParameterDeclaration.class)); - exceptions = children.get(Throws.class); - body = children.get(StatementBlock.class); - this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; - assert returnType == null || voidComments == null; - } - - + public MethodDeclaration(ExtList children, + boolean parentIsInterfaceDeclaration, + Comment[] voidComments) { + super(children); + returnType = children.get(TypeReference.class); + this.voidComments = voidComments; + name = children.get(ProgramElementName.class); + this.parameters = new ImmutableArray<>(children.collect(ParameterDeclaration.class)); + exceptions = children.get(Throws.class); + body = children.get(StatementBlock.class); + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; + assert returnType == null || voidComments == null; + } + + /** * Method declaration. - * @param modifiers a modifier array - * @param returnType a type reference. - * @param name an identifier. - * @param parameters a parameter declaration mutable list. - * @param exceptions a throws. - * @param body a statement block. + * + * @param modifiers a modifier array + * @param returnType a type reference. + * @param name an identifier. + * @param parameters a parameter declaration mutable list. + * @param exceptions a throws. + * @param body a statement block. * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * parent is an InterfaceDeclaration */ - public MethodDeclaration(Modifier[] modifiers, - TypeReference returnType, - ProgramElementName name, - ParameterDeclaration[] parameters, - Throws exceptions, - StatementBlock body, - boolean parentIsInterfaceDeclaration) { - this(modifiers, - returnType, - name, - new ImmutableArray(parameters), - exceptions, - body, - parentIsInterfaceDeclaration); - } - - + public MethodDeclaration(Modifier[] modifiers, + TypeReference returnType, + ProgramElementName name, + ParameterDeclaration[] parameters, + Throws exceptions, + StatementBlock body, + boolean parentIsInterfaceDeclaration) { + this(modifiers, + returnType, + name, + new ImmutableArray(parameters), + exceptions, + body, + parentIsInterfaceDeclaration); + } + + /** * Method declaration. - * @param modifiers a modifier array - * @param returnType a type reference. - * @param name an identifier. - * @param parameters a parameter declaration mutable list. - * @param exceptions a throws. - * @param body a statement block. + * + * @param modifiers a modifier array + * @param returnType a type reference. + * @param name an identifier. + * @param parameters a parameter declaration mutable list. + * @param exceptions a throws. + * @param body a statement block. * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * parent is an InterfaceDeclaration */ - public MethodDeclaration(Modifier[] modifiers, - TypeReference returnType, - ProgramElementName name, - ImmutableArray parameters, - Throws exceptions, - StatementBlock body, - boolean parentIsInterfaceDeclaration) { - super(modifiers); - this.returnType = returnType; - this.voidComments = null; + public MethodDeclaration(Modifier[] modifiers, + TypeReference returnType, + ProgramElementName name, + ImmutableArray parameters, + Throws exceptions, + StatementBlock body, + boolean parentIsInterfaceDeclaration) { + super(modifiers); + this.returnType = returnType; + this.voidComments = null; this.name = name; - this.parameters = parameters; + this.parameters = parameters; this.exceptions = exceptions; - this.body = body; - this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; + this.body = body; + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; } - - @Override - public ProgramElementName getProgramElementName(){ - return name; + + @Override + public ProgramElementName getProgramElementName() { + return name; } - @Override + @Nonnull + @Override public SourceElement getFirstElement() { return getChildAt(0); } - - @Override + + @Nonnull + @Override public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } @@ -162,16 +172,16 @@ public SourceElement getLastElement() { @Override public int getChildCount() { int result = 0; - if (modArray != null) result += modArray.size(); + if (modArray != null) result += modArray.size(); if (returnType != null) result++; - if (name != null) result++; + if (name != null) result++; if (parameters != null) result += parameters.size(); if (exceptions != null) result++; - if (body != null) result++; + if (body != null) result++; return result; } - + @Override public ProgramElement getChildAt(int index) { int len; @@ -213,7 +223,7 @@ public int getStatementCount() { return (body != null) ? 1 : 0; } - + @Override public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -228,7 +238,7 @@ public int getTypeReferenceCount() { return (returnType != null) ? 1 : 0; } - + @Override public TypeReference getTypeReferenceAt(int index) { if (returnType != null && index == 0) { @@ -237,13 +247,13 @@ public TypeReference getTypeReferenceAt(int index) { throw new IndexOutOfBoundsException(); } - + @Override public int getParameterDeclarationCount() { return (parameters != null) ? parameters.size() : 0; } - + @Override public ParameterDeclaration getParameterDeclarationAt(int index) { if (parameters != null) { @@ -252,22 +262,23 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { throw new IndexOutOfBoundsException(); } - + /** - * Get return type. - * @return the type reference. + * Get return type. + * + * @return the type reference. */ public TypeReference getTypeReference() { return returnType; } - - + + public Comment[] getVoidComments() { - return voidComments; + return voidComments; } - @Override + @Override public final String getName() { return (name == null) ? null : name.toString(); } @@ -277,10 +288,10 @@ public ImmutableArray getParameters() { return parameters; } - - @Override + + @Override public String getFullName() { - return getName(); + return getName(); } @@ -299,19 +310,19 @@ public boolean isFinal() { return super.isFinal(); } - + @Override public boolean isPrivate() { return super.isPrivate(); } - - @Override + + @Override public boolean isProtected() { return super.isProtected(); } - + /** * Test whether the declaration is public. Methods of interfaces * are always public. @@ -321,18 +332,18 @@ public boolean isPublic() { return parentIsInterfaceDeclaration || super.isPublic(); } - + @Override public boolean isStatic() { return super.isStatic(); } - + @Override public boolean isModel() { return super.isModel(); } - + @Override public int getStateCount() { return super.getStateCount(); @@ -340,6 +351,7 @@ public int getStateCount() { /** * test whether the declaration is a method with a variable number of arguments (i.e. the ellipsis ...) + * * @return true iff so */ public boolean isVarArgMethod() { @@ -348,23 +360,23 @@ public boolean isVarArgMethod() { return parameters.get(parameters.size() - 1).isVarArg(); } - + @Override public boolean isStrictFp() { return super.isStrictFp(); } - + /** * Test whether the declaration is abstract. Methods of interfaces * are always abstract. */ - @Override + @Override public boolean isAbstract() { - return parentIsInterfaceDeclaration || super.isAbstract(); + return parentIsInterfaceDeclaration || super.isAbstract(); } - + /** * Test whether the declaration is native. Constructors * are never native. @@ -380,13 +392,13 @@ public boolean isSynchronized() { return super.isSynchronized(); } - + @Override public void visit(Visitor v) { - v.performActionOnMethodDeclaration(this); + v.performActionOnMethodDeclaration(this); } - @Override + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printMethodDeclaration(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Throws.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Throws.java index e51568171fc..e1b2f5ff6c1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Throws.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Throws.java @@ -13,115 +13,111 @@ package de.uka.ilkd.key.java.declaration; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Throws. - * @author AutoDoc - */ - -public class Throws extends JavaNonTerminalProgramElement - implements TypeReferenceContainer { +import javax.annotation.Nonnull; +import java.util.List; +public class Throws extends JavaNonTerminalProgramElement implements TypeReferenceContainer { /** - * Exceptions. + * Exceptions. */ + @Nonnull protected final ImmutableArray exceptions; - /** - * Throws. - */ - public Throws() { - this.exceptions=null; + public Throws(PositionInfo pi, List comments, @Nonnull ImmutableArray exceptions) { + super(pi, comments); + this.exceptions = exceptions; } /** - * Throws. - * @param exception a type reference. + * Throws. + * + * @param exception a type reference. */ public Throws(TypeReference exception) { - this.exceptions=new ImmutableArray(exception); + this(null, null, new ImmutableArray<>(exception)); } /** - * Throws. - * @param list a type reference array. + * Throws. + * + * @param list a type reference array. */ public Throws(TypeReference[] list) { - this.exceptions = new ImmutableArray(list); + this(null, null, new ImmutableArray<>(list)); } - /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * several of TypeReference (as references to thrown exceptions), - * Comments + * May contain: + * several of TypeReference (as references to thrown exceptions), + * Comments */ public Throws(ExtList children) { - super(children); - this.exceptions=new - ImmutableArray(children.collect(TypeReference.class)); + super(children); + this.exceptions = new ImmutableArray<>(children.collect(TypeReference.class)); } + @Override + @Nonnull public SourceElement getLastElement() { - if (exceptions == null) { - return this; - } return exceptions.get(exceptions.size() - 1); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { int result = 0; - if (exceptions != null) result += exceptions.size(); + result += exceptions.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { - if (exceptions != null) { - return exceptions.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return exceptions.get(index); } - + /** - * Get exceptions. - * @return the type reference mutable list. + * Get exceptions. + * + * @return the type reference mutable list. */ + @Nonnull public ImmutableArray getExceptions() { return exceptions; } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { - return (exceptions != null) ? exceptions.size() : 0; + return exceptions.size(); } /* @@ -132,23 +128,25 @@ public int getTypeReferenceCount() { @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { - if (exceptions != null) { - return exceptions.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return exceptions.get(index); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnThrows(this); + v.performActionOnThrows(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printThrows(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclaration.java index db5e1e4e48e..25d384d95cf 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclaration.java @@ -35,6 +35,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; + /** * Type declaration. * taken from COMPOST and changed to achieve an immutable structure @@ -127,6 +129,7 @@ public TypeDeclaration(ExtList children, fullName, isLibrary); } + @Nonnull public SourceElement getFirstElement() { if (modArray != null && (modArray.size()>0)) { return modArray.get(0); @@ -135,6 +138,7 @@ public SourceElement getFirstElement() { } } + @Nonnull public SourceElement getLastElement() { // end of member block return this; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableDeclaration.java index 22e7519ed55..7c673172603 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableDeclaration.java @@ -13,107 +13,109 @@ package de.uka.ilkd.key.java.declaration; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.SourceElement; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Variable declaration. + * Variable declaration. * taken from COMPOST and changed to achieve an immutable structure */ - -public abstract class VariableDeclaration - extends JavaDeclaration - implements TypeReferenceContainer { +public abstract class VariableDeclaration extends JavaDeclaration implements TypeReferenceContainer { /** - * Type reference. + * Type reference. */ - protected final TypeReference typeReference; - /** this field stores if parent is an InterfaceDeclaration because we will be + /** + * this field stores if parent is an InterfaceDeclaration because we will be * unable to walk the tree upwards to check this */ protected final boolean parentIsInterfaceDeclaration; - - /** - * Variable declaration. - */ - - public VariableDeclaration() { - typeReference=null; - parentIsInterfaceDeclaration=false; + public VariableDeclaration(PositionInfo pi, List comments, @Nonnull ImmutableArray modArray, + TypeReference typeReference, boolean parentIsInterfaceDeclaration) { + super(pi, comments, modArray); + this.typeReference = typeReference; + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; } /** * Variable declaration. - * @param mods a modifier mutable list. - * @param typeRef a type reference. + * + * @param mods a modifier mutable list. + * @param typeRef a type reference. * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * the parent is an InterfaceDeclaration */ public VariableDeclaration(Modifier[] mods, TypeReference typeRef, - boolean parentIsInterfaceDeclaration) - { + boolean parentIsInterfaceDeclaration) { super(mods); - typeReference=typeRef; - this.parentIsInterfaceDeclaration=parentIsInterfaceDeclaration; + typeReference = typeRef; + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; } /** * Variable declaration. - * @param mods a modifier immutable list. - * @param typeRef a type reference. + * + * @param mods a modifier immutable list. + * @param typeRef a type reference. * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * the parent is an InterfaceDeclaration */ public VariableDeclaration(ImmutableArray mods, TypeReference typeRef, - boolean parentIsInterfaceDeclaration) - { + boolean parentIsInterfaceDeclaration) { super(mods); - typeReference=typeRef; - this.parentIsInterfaceDeclaration=parentIsInterfaceDeclaration; + typeReference = typeRef; + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; } /** * Variable declaration. - * @param children an ExtList of children. May - * include: - * a TypeReference (as reference to the type of the declared variable) - * several Modifier (taken as modifiers of the declaration), - * Comments + * + * @param children an ExtList of children. May + * include: + * a TypeReference (as reference to the type of the declared variable) + * several Modifier (taken as modifiers of the declaration), + * Comments * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * the parent is an InterfaceDeclaration */ - public VariableDeclaration(ExtList children, boolean parentIsInterfaceDeclaration) { + public VariableDeclaration(ExtList children, boolean parentIsInterfaceDeclaration) { super(children); - typeReference = children.get(TypeReference.class); - this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; + typeReference = children.get(TypeReference.class); + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; } + @Nonnull public SourceElement getFirstElement() { return getChildAt(0).getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return getChildAt(0).getFirstElementIncludingBlocks(); + return getChildAt(0).getFirstElementIncludingBlocks(); } + @Nonnull public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ public int getTypeReferenceCount() { @@ -137,8 +139,9 @@ public TypeReference getTypeReferenceAt(int index) { } /** - * Get type reference. - * @return the type reference. + * Get type reference. + * + * @return the type reference. */ public TypeReference getTypeReference() { @@ -146,8 +149,9 @@ public TypeReference getTypeReference() { } /** - * Get variables. - * @return the variable specification array wrapper + * Get variables. + * + * @return the variable specification array wrapper */ public abstract ImmutableArray getVariables(); @@ -160,19 +164,22 @@ public boolean isFinal() { return super.isFinal(); } - /** this field stores if parent is an InterfaceDeclaration because we will be + /** + * this field stores if parent is an InterfaceDeclaration because we will be * unable to walk the tree upwards to check this */ - public boolean parentIsInterfaceDeclaration () { - return parentIsInterfaceDeclaration; + public boolean parentIsInterfaceDeclaration() { + return parentIsInterfaceDeclaration; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnVariableDeclaration(this); + v.performActionOnVariableDeclaration(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableSpecification.java index 222ca2a31d0..832fc3e9c73 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/VariableSpecification.java @@ -25,6 +25,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; + /** * Variable specification that defines a variable name. This is a part of a @@ -242,11 +244,13 @@ public String getFullName() { return getName(); } + @Nonnull @Override public SourceElement getFirstElement() { return var; } + @Nonnull @Override public SourceElement getLastElement() { if (initializer != null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ArrayInitializer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ArrayInitializer.java index 9194f054619..86c6832f19c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ArrayInitializer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ArrayInitializer.java @@ -13,116 +13,114 @@ package de.uka.ilkd.key.java.expression; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * An ArrayInitializer is a valid expression exclusively for initializing - * ArrayTypes. Any other expressions are suited for any expression node. - * These rules could have been expressed by appropriate types, but these - * solutions would require a couple of new interfaces which did not seem - * adequate. - * The parent expression is either another ArrayInitializer (nested blocks) - * or a VariableDeclaration. + * An ArrayInitializer is a valid expression exclusively for initializing + * ArrayTypes. Any other expressions are suited for any expression node. + * These rules could have been expressed by appropriate types, but these + * solutions would require a couple of new interfaces which did not seem + * adequate. + * The parent expression is either another ArrayInitializer (nested blocks) + * or a VariableDeclaration. */ -public class ArrayInitializer extends JavaNonTerminalProgramElement - implements Expression, ExpressionContainer { +public final class ArrayInitializer extends JavaNonTerminalProgramElement + implements Expression, ExpressionContainer { + @Nonnull + private final ImmutableArray children; - protected final ImmutableArray children; - protected final KeYJavaType kjt; + @Nonnull + private final KeYJavaType kjt; + + public ArrayInitializer(PositionInfo pi, List comments, + @Nonnull ImmutableArray children, @Nonnull KeYJavaType kjt) { + super(pi, comments); + this.children = children; + this.kjt = kjt; + } /** - * Array initializer. - * @param list with all children. - * May contain: - * several of Expression (as the initializing expression) - * Comments + * Array initializer. + * + * @param list with all children. + * May contain: + * several of Expression (as the initializing expression) + * Comments */ - public ArrayInitializer(ExtList list, KeYJavaType kjt) { - super(list); - assert kjt != null; - this.kjt = kjt; - this.children = - new ImmutableArray(list.collect(Expression.class)); + public ArrayInitializer(ExtList list, @Nonnull KeYJavaType kjt) { + super(list); + this.kjt = kjt; + this.children = new ImmutableArray<>(list.collect(Expression.class)); } - - + + /** * create a new array initializer with the given expressions as elements. + * * @param expressions a list of all contained elements */ public ArrayInitializer(Expression[] expressions, KeYJavaType kjt) { - super(); - assert kjt != null; - this.kjt = kjt; - this.children = new ImmutableArray(expressions); + this(null, null, new ImmutableArray<>(expressions), kjt); } - + @Override public int getChildCount() { - return (children != null) ? children.size() : 0; + return children.size(); } @Override public ProgramElement getChildAt(int index) { - if (children != null) { - return children.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return children.get(index); } - + @Override public int getExpressionCount() { - return (children != null) ? children.size() : 0; + return children.size(); } - + @Override public Expression getExpressionAt(int index) { - if (children != null) { - return children.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return children.get(index); } - + @Override public void visit(Visitor v) { - v.performActionOnArrayInitializer(this); + v.performActionOnArrayInitializer(this); } - - @Override + + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printArrayInitializer(this); } - + /** - * Get arguments. - * @return the wrapped argument array + * Get arguments. + * + * @return the wrapped argument array */ public ImmutableArray getArguments() { return children; } - - @Override + + @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { return kjt; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Assignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Assignment.java index 585b02be59c..c0031f4ec7f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Assignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Assignment.java @@ -13,63 +13,79 @@ package de.uka.ilkd.key.java.expression; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.literal.BooleanLiteral; import de.uka.ilkd.key.java.reference.ExecutionContext; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; +import javax.annotation.Nonnull; +import java.util.List; -/** - * An assignment is an operator with side-effects. + +/** + * An assignment is an operator with side-effects. */ -public abstract class Assignment extends Operator - implements ExpressionStatement { +public abstract class Assignment extends Operator implements ExpressionStatement { + private Assignment(PositionInfo pi, List comments, @Nonnull ImmutableArray children) { + super(pi, comments, children); + } - public Assignment() { + protected Assignment(PositionInfo pi, List comments, @Nonnull Expression lhs) { + super(pi, comments, new ImmutableArray<>(lhs)); + } + protected Assignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, new ImmutableArray<>(lhs, rhs)); } + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * In this case the order of the children is IMPORTANT. - * May contain: - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments + * In this case the order of the children is IMPORTANT. + * May contain: + * 2 of Expression (the first Expression as left hand + * side, the second as right hand side), + * Comments */ public Assignment(ExtList children) { - super(children); + super(children); } /** - Unary Assignment (e.g. +=, ++). - @param lhs an expression. - */ - public Assignment(Expression lhs) { - super(lhs); + * Unary Assignment (e.g. +=, ++). + * + * @param lhs an expression. + */ + public Assignment(@Nonnull Expression lhs) { + this(null, null, new ImmutableArray<>(lhs)); } /** - Assignment. - @param lhs an expression. - @param rhs an expression. - */ - public Assignment(Expression lhs, Expression rhs) { - super(lhs, rhs); + * Assignment. + * + * @param lhs an expression. + * @param rhs an expression. + */ + public Assignment(@Nonnull Expression lhs, @Nonnull Expression rhs) { + this(null, null, new ImmutableArray<>(lhs, rhs)); } /** - * Checks if this operator is left or right associative. Assignments - * are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Assignments + * are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { @@ -79,30 +95,32 @@ public boolean isLeftAssociative() { /** * retrieves the type of the assignment expression + * * @param javaServ the Services offering access to the Java model - * @param ec the ExecutionContext in which the expression is evaluated + * @param ec the ExecutionContext in which the expression is evaluated * @return the type of the assignment expression */ public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return getExpressionAt(0).getKeYJavaType(javaServ, ec); + return getExpressionAt(0).getKeYJavaType(javaServ, ec); } - - /** overriden from Operator + + /** + * overriden from Operator */ public String reuseSignature(Services services, ExecutionContext ec) { - String base=super.reuseSignature(services, ec); - Expression rhs; - try{ - rhs = children.get(1); - } catch(ArrayIndexOutOfBoundsException e) { - // no second argument, e.g. PostIncrement - return base; - } - if (rhs instanceof BooleanLiteral) - return base+"["+rhs+"]"; - else - return base; + String base = super.reuseSignature(services, ec); + Expression rhs; + try { + rhs = children.get(1); + } catch (ArrayIndexOutOfBoundsException e) { + // no second argument, e.g. PostIncrement + return base; + } + if (rhs instanceof BooleanLiteral) + return base + "[" + rhs + "]"; + else + return base; } - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Literal.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Literal.java index 36197bd2968..9eb1fb85af5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Literal.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Literal.java @@ -13,49 +13,42 @@ package de.uka.ilkd.key.java.expression; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceData; -import de.uka.ilkd.key.java.TerminalProgramElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.rule.MatchConditions; -import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; /** - * Literal. - * @author AutoDoc + * Literal. + * + * @author AutoDoc */ public abstract class Literal extends JavaProgramElement implements Expression, TerminalProgramElement { - + public Literal(@Nullable PositionInfo pi, @Nullable List comments) { + super(pi, comments); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments + * May contain: Comments */ public Literal(ExtList children) { - super(children); - } - - /** - * Literal - */ - public Literal() { - + super(children); } /** * Literal with specific source code position. + * * @param children the children of this AST element as KeY classes. May contain: Comments - * @param pos The specific source code position. + * @param pos The specific source code position. */ public Literal(ExtList children, PositionInfo pos) { super(children, pos); @@ -63,31 +56,36 @@ public Literal(ExtList children, PositionInfo pos) { /** * Literal with specific source code position. + * * @param pos The specific source code position. */ public Literal(PositionInfo pos) { super(pos); } - /** retrieves the literal's type (as it is independant of the + /** + * retrieves the literal's type (as it is independant of the * execution context, it is same as using {@link #getKeYJavaType(Services)}) - * @param javaServ the Services offering access to the Java model - * @param ec the ExecutionContext in which the expression is evaluated + * + * @param javaServ the Services offering access to the Java model + * @param ec the ExecutionContext in which the expression is evaluated * @return the literal's type */ @Override - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return getKeYJavaType(javaServ); + public KeYJavaType getKeYJavaType(Services javaServ, + ExecutionContext ec) { + return getKeYJavaType(javaServ); } - - /** retrieves the literal's type - * @param javaServ the Services offering access to the Java model + + /** + * retrieves the literal's type + * + * @param javaServ the Services offering access to the Java model * @return the literal's type */ public abstract KeYJavaType getKeYJavaType(Services javaServ); - - + + @Override public MatchConditions match(SourceData source, MatchConditions matchCond) { final ProgramElement src = source.getSource(); @@ -97,12 +95,12 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { } else { LOGGER.debug("Program match failed (pattern {}, source {})", this, src); return null; - } + } } - + /* - * Return the Name of the LDT, which this Literal belongs to. - */ + * Return the Name of the LDT, which this Literal belongs to. + */ public abstract Name getLDTName(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Operator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Operator.java index 9ab26a87d4c..94eb9a68966 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Operator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/Operator.java @@ -13,104 +13,86 @@ package de.uka.ilkd.key.java.expression; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.abstraction.KeYJavaType; +import de.uka.ilkd.key.java.reference.ExecutionContext; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.reference.ExecutionContext; +import javax.annotation.Nonnull; +import java.util.List; /** - * Operator base class. - * @author AL -*/ + * Operator base class. + * + * @author AL + */ public abstract class Operator extends JavaNonTerminalProgramElement - implements Expression, ExpressionContainer { - - + implements Expression, ExpressionContainer { /** - * Children. + * Relative positioning of the operator. */ - protected final ImmutableArray children; + public static final int PREFIX = 0; + public static final int INFIX = 1; + public static final int POSTFIX = 2; /** - * Relative positioning of the operator. + * Children. */ + @Nonnull + protected final ImmutableArray children; - public static final int PREFIX = 0; - public static final int INFIX = 1; - public static final int POSTFIX = 2; + public Operator(PositionInfo pi, List comments, @Nonnull ImmutableArray children) { + super(pi, comments); + this.children = children; + } public Operator() { - this.children = null; + this(null, null, new ImmutableArray<>()); } - /** - Operator. - @param lhs an expression. - @param rhs an expression. - */ - public Operator(Expression lhs, Expression rhs) { - this.children=new ImmutableArray(lhs, rhs); - } /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * In this case the order of the children is IMPORTANT. - * May contain: - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments * + * @param children the children of this AST element as KeY classes. + * In this case the order of the children is IMPORTANT. + * May contain: + * 2 of Expression (the first Expression as left hand + * side, the second as right hand side), + * Comments */ public Operator(ExtList children) { super(children); - this.children = - new ImmutableArray - (children.collect(Expression.class)); - } - - /** - * Operator. - * @param unaryChild an expression. - */ - - public Operator(Expression unaryChild) { - this.children = new ImmutableArray(unaryChild); + this.children = new ImmutableArray<>(children.collect(Expression.class)); } /** * Operator. + * * @param arguments an array of expression. */ - - public Operator(Expression[] arguments) { - this.children = new ImmutableArray(arguments); + public Operator(Expression... arguments) { + this(null, null, new ImmutableArray<>(arguments)); } - - /** - * getArity() == getASTchildren().size() + /** + * getArity() == getASTchildren().size() */ public abstract int getArity(); - /** 0 is the "highest" precedence (obtained by parantheses), - * 13 the "lowest". + /** + * 0 is the "highest" precedence (obtained by parantheses), + * 13 the "lowest". */ public abstract int getPrecedence(); /** - * @return true, if a has a higher priority (a lower precendence value) - * than b. + * @return true, if a has a higher priority (a lower precendence value) + * than b. */ public static boolean precedes(Operator a, Operator b) { @@ -118,87 +100,90 @@ public static boolean precedes(Operator a, Operator b) { } /** - * @return INFIX, PREFIX, or POSTFIX. + * @return INFIX, PREFIX, or POSTFIX. */ public abstract int getNotation(); /** - * Checks if this operator is left or right associative. The associativity - * defines the order in which the arguments are evaluated (left-to-right - * or right-to-left). The default is left associative. Unary operators, - * assignments and conditionals are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. The associativity + * defines the order in which the arguments are evaluated (left-to-right + * or right-to-left). The default is left associative. Unary operators, + * assignments and conditionals are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { return true; } + @Nonnull public SourceElement getFirstElement() { switch (getNotation()) { - case INFIX: - case POSTFIX: - return children.get(0).getFirstElement(); - case PREFIX: - default: - return this; + case INFIX: + case POSTFIX: + return children.get(0).getFirstElement(); + case PREFIX: + default: + return this; } } @Override public SourceElement getFirstElementIncludingBlocks() { - switch (getNotation()) { - case INFIX: - case POSTFIX: - return children.get(0).getFirstElementIncludingBlocks(); - case PREFIX: - default: - return this; - } + switch (getNotation()) { + case INFIX: + case POSTFIX: + return children.get(0).getFirstElementIncludingBlocks(); + case PREFIX: + default: + return this; + } } + @Nonnull public SourceElement getLastElement() { switch (getNotation()) { - case INFIX: - case PREFIX: - return children.get(getArity() - 1).getLastElement(); + case INFIX: + case PREFIX: + return children.get(getArity() - 1).getLastElement(); case POSTFIX: - default: - return this; + default: + return this; } } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { - return (children != null) ? children.size() : 0; + return children.size(); } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (children != null) { - return children.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return children.get(index); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { - return (children != null) ? children.size() : 0; + return children.size(); } /* @@ -211,30 +196,30 @@ public int getExpressionCount() { */ public Expression getExpressionAt(int index) { - if (children != null) { - return children.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return children.get(index); } - /** return arguments */ + /** + * return arguments + */ public ImmutableArray getArguments() { - return children; + return children; } // has to be changed public boolean isToBeParenthesized() { - return false; + return false; } - - /** overriden from JavaProgramElement. + + /** + * overriden from JavaProgramElement. */ public String reuseSignature(Services services, ExecutionContext ec) { - return super.reuseSignature(services, ec)+"("+ - services.getTypeConverter().getKeYJavaType(this, ec).getName()+")"; + return super.reuseSignature(services, ec) + "(" + + services.getTypeConverter().getKeYJavaType(this, ec).getName() + ")"; } - public abstract KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec); + public abstract KeYJavaType getKeYJavaType(Services javaServ, + ExecutionContext ec); } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ParenthesizedExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ParenthesizedExpression.java index 91a59873dc8..db6931d3a5e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ParenthesizedExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ParenthesizedExpression.java @@ -12,58 +12,66 @@ // package de.uka.ilkd.key.java.expression; -import java.io.IOException; - -import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.ReferencePrefix; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.List; + +/** + * Redundant Parentheses. Modelled as a special "identity" unary "infix" + * operator. + */ -/** Redundant Parentheses. Modelled as a special "identity" unary "infix" - * operator. */ +public class ParenthesizedExpression extends Operator + implements ExpressionStatement, ReferencePrefix { -public class ParenthesizedExpression extends Operator - implements ExpressionStatement, ReferencePrefix { + public ParenthesizedExpression(PositionInfo pi, List comments, @Nonnull Expression child) { + super(pi, comments, new ImmutableArray<>(child)); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * In this case the order of the children is IMPORTANT. - * May contain: - * several of Expression (should be one, the first is taken - * as parenthesized expression), - * Comments + * In this case the order of the children is IMPORTANT. + * May contain: + * several of Expression (should be one, the first is taken + * as parenthesized expression), + * Comments */ public ParenthesizedExpression(ExtList children) { - super(children); + super(children); } - public ParenthesizedExpression(Expression child) { - super(child); + public ParenthesizedExpression(@Nonnull Expression child) { + this(null, null,child); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { return (children != null) ? children.size() : 0; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (children != null) { @@ -73,44 +81,51 @@ public ProgramElement getChildAt(int index) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { return 1; } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 0; } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; - /* Only unary infix operator;) */ + /* Only unary infix operator;) */ } + @Nonnull public SourceElement getFirstElement() { return this; } + @Nonnull public SourceElement getLastElement() { return this; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnParenthesizedExpression(this); + v.performActionOnParenthesizedExpression(this); } public void prettyPrint(PrettyPrinter w) throws IOException { @@ -120,18 +135,19 @@ public void prettyPrint(PrettyPrinter w) throws IOException { /** * We do not have a prefix, so fake it! * This way we implement ReferencePrefix + * * @author VK */ public ReferencePrefix getReferencePrefix() { - return null; + return null; } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return getExpressionAt(0).getKeYJavaType(javaServ, ec); + return getExpressionAt(0).getKeYJavaType(javaServ, ec); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/AbstractIntegerLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/AbstractIntegerLiteral.java index c91bfcff908..77486e4da72 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/AbstractIntegerLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/AbstractIntegerLiteral.java @@ -13,27 +13,29 @@ package de.uka.ilkd.key.java.expression.literal; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.NameAbstractionTable; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.SourceElement; import de.uka.ilkd.key.java.expression.Literal; import de.uka.ilkd.key.ldt.IntegerLDT; import de.uka.ilkd.key.logic.Name; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; /** * This class is a superclass for integer literals (Int, Long, Char). * It provides a getValue() method to receive the actual value of the literal as well as * getValueString() to get a String representation. Subclasses of this class perform range checks at * creation time. This means once a literal is created it is certainly valid. + * * @author Wolfram Pfeifer */ public abstract class AbstractIntegerLiteral extends Literal { - - /** - * Empty default constructor. - */ - protected AbstractIntegerLiteral() { + public AbstractIntegerLiteral(@Nullable PositionInfo pi, @Nullable List comments) { + super(pi, comments); } /** @@ -46,15 +48,13 @@ protected AbstractIntegerLiteral(ExtList children) { } /** - * * @return the actual value of the literal as a long */ public abstract long getValue(); /** - * * @return the actual value of the literal converted to a decimal String. If the literal - * represents a negative value, the first character is a '-' sign. + * represents a negative value, the first character is a '-' sign. */ public abstract String getValueString(); @@ -68,7 +68,7 @@ public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { if (!(o.getClass() == this.getClass())) { return false; } - return ((AbstractIntegerLiteral)o).getValue() == getValue(); + return ((AbstractIntegerLiteral) o).getValue() == getValue(); } @Override @@ -92,6 +92,7 @@ public Name getLDTName() { * This method does not check if the literal is actually valid, it just checks the * prefix indicating the base of the literal. The base prefix is found even if the String * contains a preceding sign ('+' or '-'). + * * @param literalStr the given String to check * @return true iff the String represents a decimal literal, which means it does neither have * a hexadecimal ("0x"), binary ("0b"), nor octal ("0") prefix. Note that the literal "0" is diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/BooleanLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/BooleanLiteral.java index b680d0882b5..e9aa31acd3e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/BooleanLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/BooleanLiteral.java @@ -13,88 +13,95 @@ package de.uka.ilkd.key.java.expression.literal; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.NameAbstractionTable; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.expression.Literal; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.ldt.BooleanLDT; import de.uka.ilkd.key.logic.Name; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; /** - * Boolean literal. - * @author AutoDoc + * Boolean literal. + * + * @author AutoDoc */ -public class BooleanLiteral extends Literal { +public final class BooleanLiteral extends Literal { + public static final BooleanLiteral TRUE = new BooleanLiteral(true); + public static final BooleanLiteral FALSE = new BooleanLiteral(false); - public final static BooleanLiteral TRUE = new BooleanLiteral(true); - public final static BooleanLiteral FALSE = new BooleanLiteral(false); + private final boolean value; + public BooleanLiteral(@Nullable PositionInfo pi, @Nullable List comments, boolean value) { + super(pi, comments); + this.value = value; + } - protected final boolean value; - - /** * get boolean literal for the given value. This supports - * use of single literals, but we do not force it. + * use of single literals, but we do not force it. + * * @param val a boolean specifying the literal to be returned * @return the BooleanLiteral representing val */ public static BooleanLiteral getBooleanLiteral(boolean val) { - return val ? TRUE : FALSE; + return val ? TRUE : FALSE; } /** - * Boolean literal. - * @param value a boolean value. + * Boolean literal. + * + * @param value a boolean value. */ private BooleanLiteral(boolean value) { - this.value=value; + this((PositionInfo) null, null, value); } /** - * Boolean literal. - * @param children list with all children - * May contain: Comments - * @param value a boolean value. + * Boolean literal. + * + * @param children list with all children + * May contain: Comments + * @param value a boolean value. */ public BooleanLiteral(ExtList children, boolean value) { - super(children); - this.value=value; + super(children); + this.value = value; } /** * Boolean literal. + * * @param children list with all children - * @param pos The source code position. - * @param value a boolean value. + * @param pos The source code position. + * @param value a boolean value. */ public BooleanLiteral(ExtList children, PositionInfo pos, boolean value) { super(children, pos); - this.value=value; + this.value = value; } /** * Boolean literal. - * @param pos The source code position. + * + * @param pos The source code position. * @param value a boolean value. */ public BooleanLiteral(PositionInfo pos, boolean value) { super(pos); - this.value=value; + this.value = value; } - /** - * Get value. - * @return the string. + /** + * Get value. + * + * @return the string. */ public boolean getValue() { @@ -102,40 +109,44 @@ public boolean getValue() { } /** - * Get value. - * @return the string. + * Get value. + * + * @return the string. */ public String getName() { - return (value ? "true" : "false") ; + return (value ? "true" : "false"); } - /** tests if equals + /** + * tests if equals */ - public boolean equalsModRenaming( SourceElement o, - NameAbstractionTable nat) { + public boolean equalsModRenaming(SourceElement o, + NameAbstractionTable nat) { if (!(o instanceof BooleanLiteral)) { return false; } - return ((BooleanLiteral)o).getValue() == getValue(); + return ((BooleanLiteral) o).getValue() == getValue(); } @Override protected int computeHashCode() { return 37 * super.computeHashCode() + (getValue() ? 0 : 1); } - + @Override - public boolean equals(Object o){ - return super.equals(o); + public boolean equals(Object o) { + return super.equals(o); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBooleanLiteral(this); + v.performActionOnBooleanLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -144,7 +155,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/CharLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/CharLiteral.java index 58ca4636bbb..81da50b595b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/CharLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/CharLiteral.java @@ -13,17 +13,22 @@ package de.uka.ilkd.key.java.expression.literal; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; /** - * Char literal. - * @author Wolfram Pfeifer + * Char literal. + * + * @author Wolfram Pfeifer */ public class CharLiteral extends AbstractIntegerLiteral { @@ -32,12 +37,18 @@ public class CharLiteral extends AbstractIntegerLiteral { */ private final char charVal; + public CharLiteral(@Nullable PositionInfo pi, @Nullable List comments, char charVal) { + super(pi, comments); + this.charVal = charVal; + } + /** * Creates a new CharLiteral from the given char. + * * @param charVal a char value. */ public CharLiteral(char charVal) { - this.charVal = charVal; + this(null, null, charVal); } /** @@ -46,7 +57,7 @@ public CharLiteral(char charVal) { * chars written directly (like 'a', '0', 'Z'), Java escape chars (like '\n', '\r'), and * octal Unicode escapes (like '\040'). Note that unicode escapes in hexadecimal form are * processed earlier and don't have to be handled here. - * + *

* Note that the char must be enclosed in single-quotes. * * @param children an ExtList with all children(comments). May contain: Comments @@ -60,14 +71,16 @@ public CharLiteral(ExtList children, String valueStr) { /** * Creates a new CharLiteral from the given String. The String must be of the form * 'c' (with c being an arbitrary char). + * * @param valueStr a string. */ public CharLiteral(String valueStr) { - this.charVal = parseFromString(valueStr); + this(null, null, parseFromString(valueStr)); } /** * Returns the decimal value of the char. + * * @return the decimal value of the char as a BigInteger */ public long getValue() { @@ -98,7 +111,7 @@ public String toString() { @Override public String getValueString() { // the char value as a decimal number (without single-quotes) - return "" + (int)charVal; + return "" + (int) charVal; } /** @@ -107,17 +120,17 @@ public String getValueString() { * chars written directly (like 'a', '0', 'Z'), Java escape chars (like '\n', '\r'), and * octal Unicode escapes (like '\040'). Note that unicode escapes in hexadecimal form are * processed earlier and don't have to be handled by this method. - * + *

* This method does not check the length of the literal for validity. * * @param sourceStr the String containing the literal surrounded by single-quotes * @return the parsed value as a char * @throws NumberFormatException if the given String does not represent a syntactically valid - * character literal or the literal is not surrounded by single-quotes + * character literal or the literal is not surrounded by single-quotes * @see - * https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.4 + * https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.4 */ - protected char parseFromString(final String sourceStr) { + protected static char parseFromString(final String sourceStr) { if (sourceStr.charAt(0) != '\'' || sourceStr.charAt(sourceStr.length() - 1) != '\'') { throw new NumberFormatException("Invalid char delimiters: " + sourceStr); } @@ -132,35 +145,35 @@ protected char parseFromString(final String sourceStr) { */ if (valStr.charAt(0) == '\\') { switch (valStr.charAt(1)) { - case 'b': - return '\b'; - case 't': - return '\t'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case 'r': - return '\r'; - case '\"': - return '\"'; - case '\'': - return '\''; - case '\\': - return '\\'; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - return (char) Integer.parseInt(valStr.substring(1), 8); - case 'u': - return (char) Integer.parseInt(valStr.substring(2), 16); - default: - throw new NumberFormatException("Invalid char: " + sourceStr); + case 'b': + return '\b'; + case 't': + return '\t'; + case 'n': + return '\n'; + case 'f': + return '\f'; + case 'r': + return '\r'; + case '\"': + return '\"'; + case '\'': + return '\''; + case '\\': + return '\\'; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + return (char) Integer.parseInt(valStr.substring(1), 8); + case 'u': + return (char) Integer.parseInt(valStr.substring(2), 16); + default: + throw new NumberFormatException("Invalid char: " + sourceStr); } } else { return valStr.charAt(0); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/DoubleLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/DoubleLiteral.java index 0ebdd530087..46302643db9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/DoubleLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/DoubleLiteral.java @@ -13,104 +13,99 @@ package de.uka.ilkd.key.java.expression.literal; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.NameAbstractionTable; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.expression.Literal; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.ldt.DoubleLDT; import de.uka.ilkd.key.logic.Name; +import org.key_project.util.ExtList; -/** - * Double literal. - * @author AutoDoc - */ - -public class DoubleLiteral extends Literal { - - /** - * Textual representation of the value. - */ - - protected final String value; +import javax.annotation.Nullable; +import java.util.List; +public final class DoubleLiteral extends Literal { /** - * Double literal. + * Textual representation of the value. */ + private final String value; - public DoubleLiteral() { - this.value="0.0"; + public DoubleLiteral(@Nullable PositionInfo pi, @Nullable List comments, String value) { + super(pi, comments); + this.value = value; } /** - * Double literal. - * @param value a double value. + * Double literal. + * + * @param value a double value. */ - public DoubleLiteral(double value) { - this.value="" + value; + this(null, null, "" + value); } /** - * Double literal. - * @param children list with all children(here:comments) - * May contain: Comments - * @param value a string. + * Double literal. + * + * @param children list with all children(here:comments) + * May contain: Comments + * @param value a string. */ public DoubleLiteral(ExtList children, String value) { - super(children); - this.value=value; + super(children); + this.value = value; } /** - * Double literal. - * @param value a string. + * Double literal. + * + * @param value a string. */ public DoubleLiteral(String value) { - this.value=value; + this(null, null, value); } - /** tests if equals + /** + * tests if equals */ - public boolean equalsModRenaming( SourceElement o, - NameAbstractionTable nat) { - if (!(o instanceof DoubleLiteral)) { - return false; - } - return ((DoubleLiteral)o).getValue().equals(getValue()); + public boolean equalsModRenaming(SourceElement o, + NameAbstractionTable nat) { + if (!(o instanceof DoubleLiteral)) { + return false; + } + return ((DoubleLiteral) o).getValue().equals(getValue()); } - + @Override - protected int computeHashCode(){ + protected int computeHashCode() { return 37 * super.computeHashCode() + getValue().hashCode(); } - - public boolean equals(Object o){ - return super.equals(o); + + public boolean equals(Object o) { + return super.equals(o); } /** - * Get value. - * @return the string. + * Get value. + * + * @return the string. */ public String getValue() { return value; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnDoubleLiteral(this); + v.performActionOnDoubleLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -118,7 +113,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/IntLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/IntLiteral.java index 615e6f1bc04..239dd1e4cc2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/IntLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/IntLiteral.java @@ -13,17 +13,22 @@ package de.uka.ilkd.key.java.expression.literal; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; /** - * Int literal. - * @author AutoDoc + * Int literal. + * + * @author AutoDoc */ public class IntLiteral extends AbstractIntegerLiteral { @@ -39,18 +44,31 @@ public class IntLiteral extends AbstractIntegerLiteral { */ private final String valueStr; + /** * The actual value of the literal. */ private final int value; + public IntLiteral(@Nullable PositionInfo pi, @Nullable List comments, int value) { + super(pi, comments); + this.value = value; + this.valueStr = "" + value; + } + + public IntLiteral(@Nullable PositionInfo pi, @Nullable List comments, String valueStr) { + super(pi, comments); + this.valueStr = valueStr; + value = parseFromString(valueStr); + } + /** * Creates a new IntLiteral representing the given int. + * * @param value the int value represented by the literal */ public IntLiteral(int value) { - this.value = value; - this.valueStr = ("" + value).intern(); + this(null, null, value); } /** @@ -61,22 +79,21 @@ public IntLiteral(int value) { * * @param valStr the String that contains the literal * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of int range + * literal or represents a value out of int range * @see - * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 + * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 */ public IntLiteral(String valStr) { - this.value = parseFromString(valStr); - this.valueStr = Integer.toString(value).intern(); + this(null, null, parseFromString(valStr)); } /** * Constructor for Recoder2KeY transformation. * * @param children the children of this AST element as KeY classes, may contain: Comments - * @param valStr the value of the literal + * @param valStr the value of the literal * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of int range + * literal or represents a value out of int range */ public IntLiteral(ExtList children, String valStr) { super(children); @@ -121,11 +138,11 @@ public String getValueString() { * @param sourceStr the String containing the value * @return the parsed value as a long * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of int range + * literal or represents a value out of int range * @see - * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 + * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 */ - protected int parseFromString(final String sourceStr) throws NumberFormatException { + protected static int parseFromString(final String sourceStr) throws NumberFormatException { String valStr = sourceStr; int radix = 10; @@ -193,6 +210,6 @@ protected int parseFromString(final String sourceStr) throws NumberFormatExcepti /* perform the actual conversion (two's complement for bin, oct and hex!) of the * BigInteger to a String containing the real (checked valid) value of the literal */ - return (int)val; // the cast does the two's complement conversion + return (int) val; // the cast does the two's complement conversion } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/LongLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/LongLiteral.java index acb56f988ad..70e2999cdc2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/LongLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/LongLiteral.java @@ -13,20 +13,18 @@ package de.uka.ilkd.key.java.expression.literal; -import java.math.BigInteger; - -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Long literal. - * @author AutoDoc - */ +import javax.annotation.Nullable; +import java.math.BigInteger; +import java.util.List; public class LongLiteral extends AbstractIntegerLiteral { @@ -57,13 +55,25 @@ public class LongLiteral extends AbstractIntegerLiteral { */ private final long value; + public LongLiteral(@Nullable PositionInfo pi, @Nullable List comments, String valueStr) { + super(pi, comments); + this.valueStr = valueStr; + value = parseFromString(valueStr); + } + + public LongLiteral(@Nullable PositionInfo pi, @Nullable List comments, long value) { + super(pi, comments); + this.value = value; + valueStr = (Long.toString(value) + 'L').intern(); + } + /** * Creates a new LongLiteral representing the given long. + * * @param value the long value represented by the literal */ public LongLiteral(long value) { - this.value = value; - this.valueStr = (Long.toString(value) + 'L').intern(); + this(null, null, value); } /** @@ -74,22 +84,21 @@ public LongLiteral(long value) { * * @param valStr the String that contains the literal * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of long range + * literal or represents a value out of long range * @see - * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 + * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 */ public LongLiteral(String valStr) { - this.value = parseFromString(valStr); - this.valueStr = (Long.toString(value) + 'L').intern(); + this(null, null, valStr); } /** * Constructor for Recoder2KeY transformation. * * @param children the children of this AST element as KeY classes, may contain: Comments - * @param valStr the value of the literal + * @param valStr the value of the literal * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of long range + * literal or represents a value out of long range */ public LongLiteral(ExtList children, String valStr) { super(children); @@ -118,10 +127,9 @@ public long getValue() { } /** - * * @return the actual value of the literal converted to a decimal String. If the literal - * represents a negative value, the first character is a '-' sign. - * The returned String always ends with 'L' to indicate a long. + * represents a negative value, the first character is a '-' sign. + * The returned String always ends with 'L' to indicate a long. */ @Override public String getValueString() { @@ -140,9 +148,9 @@ public String getValueString() { * @param sourceStr the String containing the value * @return the parsed value as a long * @throws NumberFormatException if the given String does not represent a syntactically valid - * literal or represents a value out of long range + * literal or represents a value out of long range * @see - * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 + * http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1 */ protected long parseFromString(final String sourceStr) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/NullLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/NullLiteral.java index c58d8abac2d..4a6e495c54f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/NullLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/NullLiteral.java @@ -13,6 +13,8 @@ package de.uka.ilkd.key.java.expression.literal; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -20,37 +22,38 @@ import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.Name; +import javax.annotation.Nullable; +import java.util.List; + /** - * Null literal. - * Is used as singleton. + * Null literal. + * Is used as singleton. */ public class NullLiteral extends Literal { + public static final NullLiteral NULL = new NullLiteral(null,null); - public static final NullLiteral NULL = new NullLiteral(); - - /** - * Constructor for the transformation of COMPOST ASTs to KeY. - */ - private NullLiteral() { - super(); + public NullLiteral(@Nullable PositionInfo pi, @Nullable List comments) { + super(pi, comments); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnNullLiteral(this); + v.performActionOnNullLiteral(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printNullLiteral(this); } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getNullType(); + return javaServ.getJavaInfo().getNullType(); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAnd.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAnd.java index d2ddbf8a711..26d0d7744c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAnd.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAnd.java @@ -13,40 +13,41 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Binary and. + * Binary and. */ public class BinaryAnd extends BinaryOperator { + public BinaryAnd(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Binary and. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Binary and. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ - public BinaryAnd(ExtList children) { super(children); } - /** - * Get arity. - * @return the int value. - */ - - public final int getArity() { - return 2; - } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public final int getPrecedence() { @@ -54,20 +55,23 @@ public final int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public final int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryAnd(this); + v.performActionOnBinaryAnd(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAndAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAndAssignment.java index 2a00442b0a1..1e644566257 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAndAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAndAssignment.java @@ -13,24 +13,28 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Binary and assignment. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; public class BinaryAndAssignment extends Assignment { + public BinaryAndAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } - - /* Binary and assignement - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + /** + * Binary and assignement + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public BinaryAndAssignment(ExtList children) { super(children); @@ -38,8 +42,9 @@ public BinaryAndAssignment(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -47,8 +52,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -56,20 +62,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryAndAssignment(this); + v.performActionOnBinaryAndAssignment(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryNot.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryNot.java index d95f5e1376d..70b8d14316d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryNot.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryNot.java @@ -13,37 +13,42 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Binary not. - * @author AutoDoc + * Binary not. + * + * @author AutoDoc */ public class BinaryNot extends Operator { + public BinaryNot(PositionInfo pi, List comments, @Nonnull Expression argument) { + super(pi, comments, new ImmutableArray<>(argument)); + } /** - * Binary not. - * @param children list withh all children + * Binary not. + * + * @param children list withh all children */ - public BinaryNot(ExtList children) { super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -51,8 +56,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -60,8 +66,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -69,10 +76,11 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Ordinary - * unary operators are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Ordinary + * unary operators are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { @@ -80,12 +88,14 @@ public boolean isLeftAssociative() { } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryNot(this); + v.performActionOnBinaryNot(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -93,9 +103,9 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc=javaServ.getTypeConverter(); - return tc.getPromotedType - (tc.getKeYJavaType((Expression)getChildAt(0), ec)); - + final TypeConverter tc = javaServ.getTypeConverter(); + return tc.getPromotedType + (tc.getKeYJavaType((Expression) getChildAt(0), ec)); + } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOperator.java index 700e3ccdc75..fec66da47e5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOperator.java @@ -13,46 +13,52 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Operator of arity 2 - * @author AL + * Operator of arity 2 + * + * @author AL */ public abstract class BinaryOperator extends Operator { public BinaryOperator(ExtList children) { - super(children); + super(children); + } + + public BinaryOperator(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, new ImmutableArray<>(lhs, rhs)); } public BinaryOperator(Expression lhs, Expression rhs) { - super(lhs, rhs); + this(null, null, lhs, rhs); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ - public int getArity() { + public final int getArity() { return 2; } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc=javaServ.getTypeConverter(); - try { - return tc.getPromotedType - (tc.getKeYJavaType((Expression)getChildAt(0), ec), - tc.getKeYJavaType((Expression)getChildAt(1), ec)); - } catch (Exception e){ - throw new RuntimeException("Type promotion failed (see below). Operator was "+this, e); - } + final TypeConverter tc = javaServ.getTypeConverter(); + try { + return tc.getPromotedType + (tc.getKeYJavaType((Expression) getChildAt(0), ec), + tc.getKeYJavaType((Expression) getChildAt(1), ec)); + } catch (Exception e) { + throw new RuntimeException("Type promotion failed (see below). Operator was " + this, e); + } } - } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOr.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOr.java index 6a1aa207e8b..80265f91671 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOr.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOr.java @@ -13,24 +13,28 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Binary or. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; -public class BinaryOr extends BinaryOperator { +public class BinaryOr extends BinaryOperator { + public BinaryOr(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Binary or. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Binary or. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public BinaryOr(ExtList children) { @@ -38,10 +42,10 @@ public BinaryOr(ExtList children) { } - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -49,20 +53,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryOr(this); + v.performActionOnBinaryOr(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOrAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOrAssignment.java index 91fe7f656af..b720a4886e4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOrAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOrAssignment.java @@ -13,26 +13,18 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; - -/** - * Binary or assignment. - * @author AutoDoc - */ +import org.key_project.util.ExtList; public class BinaryOrAssignment extends Assignment { - - - /** - * Binary or assignment. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Binary or assignment. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public BinaryOrAssignment(ExtList children) { @@ -41,8 +33,9 @@ public BinaryOrAssignment(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -50,8 +43,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -59,20 +53,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryOrAssignment(this); + v.performActionOnBinaryOrAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOr.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOr.java index 0562968ff14..ad526f212aa 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOr.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOr.java @@ -13,34 +13,37 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Binary X or. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; public class BinaryXOr extends BinaryOperator { - + public BinaryXOr(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Binary X or. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Binary X or. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ - public BinaryXOr(ExtList children) { super(children); } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -48,20 +51,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryXOr(this); + v.performActionOnBinaryXOr(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOrAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOrAssignment.java index ce21471f028..3b7a6d87ec0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOrAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryXOrAssignment.java @@ -13,25 +13,29 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Binary X or assignment. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; -public class BinaryXOrAssignment extends Assignment { +public class BinaryXOrAssignment extends Assignment { + public BinaryXOrAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Binary X or assignment. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Binary X or assignment. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public BinaryXOrAssignment(ExtList children) { @@ -39,8 +43,9 @@ public BinaryXOrAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -48,8 +53,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -57,20 +63,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBinaryXOrAssignment(this); + v.performActionOnBinaryXOrAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ComparativeOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ComparativeOperator.java index ce5c1789d4d..57f35a4aac5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ComparativeOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ComparativeOperator.java @@ -13,26 +13,34 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; + /** - * Comparative operator. - * @author AutoDoc + * Comparative operator. + * + * @author AutoDoc */ -public abstract class ComparativeOperator extends Operator { - +public abstract class ComparativeOperator extends BinaryOperator { + public ComparativeOperator(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Comparative operator. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Comparative operator. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public ComparativeOperator(ExtList children) { @@ -40,33 +48,25 @@ public ComparativeOperator(ExtList children) { } public ComparativeOperator(Expression lhs, Expression rhs) { - super(lhs, rhs); + this(null, null, lhs, rhs); } /** - * Get arity. - * @return the int value. + * Get notation. + * + * @return the int value. */ - - public int getArity() { - return 2; - } - - /** - * Get notation. - * @return the int value. - */ - public int getNotation() { return INFIX; } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return getKeYJavaType(services); + return getKeYJavaType(services); } + public KeYJavaType getKeYJavaType(Services services) { - return services.getTypeConverter().getBooleanType(); + return services.getTypeConverter().getBooleanType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Conditional.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Conditional.java index f4bd116782a..23d86c19c00 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Conditional.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Conditional.java @@ -13,36 +13,41 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** The most weird ternary C operator ?: */ - -public class Conditional extends Operator { +import java.util.List; +/** + * The most weird ternary C operator ?: + */ +public final class Conditional extends Operator { + public Conditional(PositionInfo pi, List comments, + Expression cond, Expression then, Expression otherwise) { + super(pi, comments, new ImmutableArray<>(cond, then, otherwise)); + } /** - * Conditional. - * @param children list of children the first one is the guard expression, - * the second one the then expression and the last one the else expr. + * Conditional. + * + * @param children list of children the first one is the guard expression, + * the second one the then expression and the last one the else expr. */ - public Conditional(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -50,8 +55,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -59,8 +65,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -68,22 +75,25 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Conditionals - * are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Conditionals + * are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { return false; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnConditional(this); + v.performActionOnConditional(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -91,46 +101,46 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc = javaServ.getTypeConverter(); - final KeYJavaType type1 = tc.getKeYJavaType(getExpressionAt(1), ec); - final KeYJavaType type2 = tc.getKeYJavaType(getExpressionAt(2), ec); - if (tc.isIdentical(type1, type2)) - return type1; - - // numeric types - if (tc.isNumericalType(type1) && - tc.isNumericalType(type2) ) { - if (type1.getJavaType() == PrimitiveType.JAVA_BYTE && - type2.getJavaType() == PrimitiveType.JAVA_SHORT || - type1.getJavaType() == PrimitiveType.JAVA_SHORT && - type2.getJavaType() == PrimitiveType.JAVA_BYTE) - return javaServ.getJavaInfo(). - getKeYJavaType(PrimitiveType.JAVA_SHORT); - if (tc.isImplicitNarrowing(getExpressionAt(1), - (PrimitiveType)type2.getJavaType())) - return type2; - if (tc.isImplicitNarrowing(getExpressionAt(2), - (PrimitiveType)type1.getJavaType())) - return type1; - return tc.getPromotedType(type1, type2); - } - - - // reference types - if (tc.isNullType(type1) && - tc.isReferenceType(type2)) - return type2; - if (tc.isNullType(type2) && - tc.isReferenceType(type1)) - return type1; - if (tc.isAssignableTo(type1, type2)) - return type2; - if (tc.isAssignableTo(type2, type1)) - return type1; - - throw new RuntimeException("Could not determine type of conditional "+ - "expression\n"+this+". This usually means that "+ - "the Java program is not compilable."); + final TypeConverter tc = javaServ.getTypeConverter(); + final KeYJavaType type1 = tc.getKeYJavaType(getExpressionAt(1), ec); + final KeYJavaType type2 = tc.getKeYJavaType(getExpressionAt(2), ec); + if (tc.isIdentical(type1, type2)) + return type1; + + // numeric types + if (tc.isNumericalType(type1) && + tc.isNumericalType(type2)) { + if (type1.getJavaType() == PrimitiveType.JAVA_BYTE && + type2.getJavaType() == PrimitiveType.JAVA_SHORT || + type1.getJavaType() == PrimitiveType.JAVA_SHORT && + type2.getJavaType() == PrimitiveType.JAVA_BYTE) + return javaServ.getJavaInfo(). + getKeYJavaType(PrimitiveType.JAVA_SHORT); + if (tc.isImplicitNarrowing(getExpressionAt(1), + (PrimitiveType) type2.getJavaType())) + return type2; + if (tc.isImplicitNarrowing(getExpressionAt(2), + (PrimitiveType) type1.getJavaType())) + return type1; + return tc.getPromotedType(type1, type2); + } + + + // reference types + if (tc.isNullType(type1) && + tc.isReferenceType(type2)) + return type2; + if (tc.isNullType(type2) && + tc.isReferenceType(type1)) + return type1; + if (tc.isAssignableTo(type1, type2)) + return type2; + if (tc.isAssignableTo(type2, type1)) + return type1; + + throw new RuntimeException("Could not determine type of conditional " + + "expression\n" + this + ". This usually means that " + + "the Java program is not compilable."); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/CopyAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/CopyAssignment.java index 3679b6aef77..e42ffb9f339 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/CopyAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/CopyAssignment.java @@ -13,68 +13,78 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; -/** - * Copy assignment. - * @author AutoDoc - */ public class CopyAssignment extends Assignment { + public CopyAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. */ public CopyAssignment(ExtList children) { - super(children); + super(children); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param lhs the Expression the value is assigned to * @param rhs the Expression the value which is assigned to lhs */ public CopyAssignment(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { return 2; } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 13; } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnCopyAssignment(this); + v.performActionOnCopyAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Divide.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Divide.java index 8b31ac4d59f..27a102b455f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Divide.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Divide.java @@ -13,37 +13,41 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import javax.annotation.Nonnull; +import java.util.List; -/** - * Divide. - */ public class Divide extends BinaryOperator { + public Divide(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Divide. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Divide. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ - public Divide(ExtList children) { super(children); } public Divide(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -51,20 +55,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnDivide(this); + v.performActionOnDivide(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DivideAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DivideAssignment.java index d249c1906d0..6e5700c09a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DivideAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DivideAssignment.java @@ -13,26 +13,29 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Divide assignment. - * @author AutoDoc - */ - -public class DivideAssignment extends Assignment { +import javax.annotation.Nonnull; +import java.util.List; +public class DivideAssignment extends Assignment { + public DivideAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Divide assignment. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Divide assignment. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public DivideAssignment(ExtList children) { @@ -40,8 +43,9 @@ public DivideAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -49,8 +53,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -58,20 +63,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnDivideAssignment(this); + v.performActionOnDivideAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Equals.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Equals.java index ae86fe63a54..18a5436348d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Equals.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Equals.java @@ -13,23 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Equals. - */ +import javax.annotation.Nonnull; +import java.util.List; public class Equals extends ComparativeOperator { + public Equals(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Equals. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Equals. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public Equals(ExtList children) { super(children); @@ -37,28 +41,32 @@ public Equals(ExtList children) { /** * Creates the equals expression lhs==rhs + * * @param lhs the Expression on the left side of the comparison * @param rhs the Expression on the right side of the comparison */ public Equals(Expression lhs, Expression rhs) { - super (lhs, rhs); + super(lhs, rhs); } - + /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 6; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnEquals(this); + v.performActionOnEquals(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ExactInstanceof.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ExactInstanceof.java index 00e851372e5..6fc3d2a46e9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ExactInstanceof.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ExactInstanceof.java @@ -22,6 +22,8 @@ import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * Instanceof. * @author AutoDoc @@ -58,6 +60,7 @@ public int getChildCount() { return result; } + @Nonnull public SourceElement getLastElement() { return typeReference; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterOrEquals.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterOrEquals.java index eff19edecbc..a207c5e0153 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterOrEquals.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterOrEquals.java @@ -13,23 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Greater or equals. - */ +import javax.annotation.Nonnull; +import java.util.List; public class GreaterOrEquals extends ComparativeOperator { - + public GreaterOrEquals(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Greater or equals. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Greater or equals. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public GreaterOrEquals(ExtList children) { @@ -37,20 +41,23 @@ public GreaterOrEquals(ExtList children) { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 5; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnGreaterOrEquals(this); + v.performActionOnGreaterOrEquals(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterThan.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterThan.java index 8c39977c25d..978b166c831 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterThan.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/GreaterThan.java @@ -13,24 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Greater than. - */ +import javax.annotation.Nonnull; +import java.util.List; public class GreaterThan extends ComparativeOperator { - + public GreaterThan(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Greater than. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Greater than. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public GreaterThan(ExtList children) { @@ -39,6 +42,7 @@ public GreaterThan(ExtList children) { /** * Greater than. + * * @param lhs the expression that is checked to be greater than rhs * @param rhs the expression that is checked to be less than lhs */ @@ -47,20 +51,23 @@ public GreaterThan(Expression lhs, Expression rhs) { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 5; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnGreaterThan(this); + v.performActionOnGreaterThan(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Instanceof.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Instanceof.java index 547a541e814..14c139a1705 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Instanceof.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Instanceof.java @@ -13,34 +13,38 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Instanceof. - * @author AutoDoc + * Instanceof. + * + * @author AutoDoc */ public class Instanceof extends TypeOperator { + public Instanceof(PositionInfo pi, List comments, + @Nonnull Expression child, TypeReference typeReference) { + super(pi, comments, new ImmutableArray<>(child), typeReference); + } /** - * Instanceof. - * @param children an ExtList with all children of this node - * the first children in list will be the expression on the left - * side, the second the one on the right side a type reference. + * Instanceof. + * + * @param children an ExtList with all children of this node + * the first children in list will be the expression on the left + * side, the second the one on the right side a type reference. */ - public Instanceof(ExtList children) { super(children); assert getChildCount() == 2 : "not 2 children but " + getChildCount(); @@ -53,9 +57,10 @@ public Instanceof(Expression unaryChild, TypeReference typeref) { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; @@ -64,18 +69,20 @@ public int getChildCount() { return result; } + @Nonnull public SourceElement getLastElement() { return typeReference; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ public ProgramElement getChildAt(int index) { int len; @@ -93,8 +100,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -102,8 +110,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -111,20 +120,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return POSTFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnInstanceof(this); + v.performActionOnInstanceof(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -132,11 +144,11 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return getKeYJavaType(javaServ); + return getKeYJavaType(javaServ); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Intersect.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Intersect.java index a899b2a0dec..c2210d67186 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Intersect.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Intersect.java @@ -13,12 +13,21 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; + public class Intersect extends BinaryOperator { + public Intersect(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public Intersect(ExtList children) { super(children); @@ -36,10 +45,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnIntersect(this); + v.performActionOnIntersect(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printIntersect(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessOrEquals.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessOrEquals.java index 651d5e62587..d7757f24059 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessOrEquals.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessOrEquals.java @@ -13,24 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Less or equals. - */ +import javax.annotation.Nonnull; +import java.util.List; public class LessOrEquals extends ComparativeOperator { - + public LessOrEquals(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Less or equals. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Less or equals. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public LessOrEquals(ExtList children) { @@ -43,20 +46,23 @@ public LessOrEquals(Expression lhs, Expression rhs) { /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 5; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnLessOrEquals(this); + v.performActionOnLessOrEquals(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessThan.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessThan.java index ca46860bb48..39a047b91ad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessThan.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LessThan.java @@ -13,24 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Less than. - */ +import javax.annotation.Nonnull; +import java.util.List; public class LessThan extends ComparativeOperator { - + public LessThan(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Less than. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Less than. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public LessThan(ExtList children) { super(children); @@ -38,6 +41,7 @@ public LessThan(ExtList children) { /** * Less than. + * * @param lhs the expression that is checked to be less than rhs * @param rhs the expression that is checked to be greater than lhs */ @@ -47,6 +51,7 @@ public LessThan(Expression lhs, Expression rhs) { /** * Get precedence. + * * @return the int value. */ @@ -54,12 +59,14 @@ public int getPrecedence() { return 5; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnLessThan(this); + v.performActionOnLessThan(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalAnd.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalAnd.java index 5bd61a36608..201566b255f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalAnd.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalAnd.java @@ -13,28 +13,30 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Logical and. + * Logical and. */ -public class LogicalAnd extends Operator { - +public class LogicalAnd extends BinaryOperator { + public LogicalAnd(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Logical and. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Logical and. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public LogicalAnd(ExtList children) { @@ -42,42 +44,36 @@ public LogicalAnd(ExtList children) { } public LogicalAnd(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get arity. - * @return the int value. + * Get precedence. + * + * @return the int value. */ - public int getArity() { - return 2; - } - - /** - * Get precedence. - * @return the int value. - */ - public int getPrecedence() { return 10; } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ - public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnLogicalAnd(this); + v.performActionOnLogicalAnd(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -85,7 +81,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return services.getTypeConverter().getBooleanType(); + return services.getTypeConverter().getBooleanType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalNot.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalNot.java index c3f7f93a722..054b0c31256 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalNot.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalNot.java @@ -13,27 +13,28 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Logical not. - */ +import javax.annotation.Nonnull; +import java.util.List; public class LogicalNot extends Operator { - + public LogicalNot(PositionInfo pi, List comments, @Nonnull Expression child) { + super(pi, comments, new ImmutableArray<>(child)); + } /** - * Logical not. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Logical not. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public LogicalNot(ExtList children) { @@ -42,8 +43,9 @@ public LogicalNot(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -51,8 +53,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -60,8 +63,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -69,22 +73,25 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Ordinary - * unary operators are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Ordinary + * unary operators are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { return false; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnLogicalNot(this); + v.performActionOnLogicalNot(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -92,7 +99,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return services.getTypeConverter().getBooleanType(); + return services.getTypeConverter().getBooleanType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalOr.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalOr.java index b6a9f00b4b0..6ea5622384a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalOr.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/LogicalOr.java @@ -13,26 +13,24 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Logical or. + * Logical or. */ -public class LogicalOr extends Operator { - - /** - * Logical or. - */ +public class LogicalOr extends BinaryOperator { + public LogicalOr(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public LogicalOr(ExtList children) { super(children); @@ -40,22 +38,14 @@ public LogicalOr(ExtList children) { public LogicalOr(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get arity. - * @return the int value. - */ - - public int getArity() { - return 2; - } - - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -63,20 +53,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnLogicalOr(this); + v.performActionOnLogicalOr(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -84,6 +77,6 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return services.getTypeConverter().getBooleanType(); + return services.getTypeConverter().getBooleanType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Minus.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Minus.java index 2a1a8af386a..cafd566cbad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Minus.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Minus.java @@ -13,39 +13,41 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Minus. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; public class Minus extends BinaryOperator { - + public Minus(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Minus. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Minus. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ - public Minus(ExtList children) { super(children); } public Minus(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -53,20 +55,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnMinus(this); + v.performActionOnMinus(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -74,5 +79,4 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } - } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/MinusAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/MinusAssignment.java index afc2f7fa19d..fdffab3fbfc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/MinusAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/MinusAssignment.java @@ -13,17 +13,26 @@ package de.uka.ilkd.key.java.expression.operator; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import org.key_project.util.ExtList; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; + /** * Minus assignment. */ public class MinusAssignment extends Assignment { + public MinusAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** * Minus assignment. diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Modulo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Modulo.java index 1ccaecde791..816628d6da0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Modulo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Modulo.java @@ -13,58 +13,58 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; - -/** - * Modulo. - */ -public class Modulo extends BinaryOperator { +import javax.annotation.Nonnull; +import java.util.List; - /** - * Modulo. - */ +public final class Modulo extends BinaryOperator { + public Modulo(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public Modulo(ExtList children) { super(children); } public Modulo(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } - - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ - public int getPrecedence() { return 2; } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnModulo(this); + v.performActionOnModulo(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ModuloAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ModuloAssignment.java index a273b6e7400..0b73b78f2a7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ModuloAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ModuloAssignment.java @@ -13,24 +13,32 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Modulo assignment. + * Modulo assignment. */ public class ModuloAssignment extends Assignment { - + public ModuloAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Modulo assignment. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Modulo assignment. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public ModuloAssignment(ExtList children) { @@ -38,8 +46,9 @@ public ModuloAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -47,8 +56,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -56,20 +66,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnModuloAssignment(this); + v.performActionOnModuloAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Negative.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Negative.java index c8c619e2fc3..5132c5ab1cd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Negative.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Negative.java @@ -13,28 +13,28 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; - -/** - * Negative. - */ +import javax.annotation.Nonnull; +import java.util.List; public class Negative extends Operator { + public Negative(PositionInfo pi, List comments, @Nonnull Expression child) { + super(pi, comments, new ImmutableArray<>(child)); + } /** - * Negative. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Negative. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public Negative(ExtList children) { @@ -43,21 +43,22 @@ public Negative(ExtList children) { public Negative(Expression expr) { - super(expr); + super(expr); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ - public int getArity() { return 1; } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -65,8 +66,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -74,22 +76,25 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Ordinary - * unary operators are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Ordinary + * unary operators are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { return false; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnNegative(this); + v.performActionOnNegative(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -97,8 +102,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return services.getTypeConverter(). - getPromotedType(getExpressionAt(0).getKeYJavaType(services, ec)); + return services.getTypeConverter(). + getPromotedType(getExpressionAt(0).getKeYJavaType(services, ec)); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/New.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/New.java index 1c8e3527ea3..0dbb2fc4b4f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/New.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/New.java @@ -30,6 +30,8 @@ import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * The object allocation operator. * There are two variants for New: @@ -109,7 +111,8 @@ public New(Expression[] arguments, TypeReference type, ReferencePrefix rp) { } - @Override + @Nonnull + @Override public SourceElement getFirstElement() { return (accessPath != null) ? accessPath.getFirstElement() : this; } @@ -120,7 +123,8 @@ public SourceElement getFirstElementIncludingBlocks() { } - @Override + @Nonnull + @Override public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NewArray.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NewArray.java index d3bb9fb23a9..b2cba59fc9a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NewArray.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NewArray.java @@ -27,6 +27,8 @@ import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * The array allocation operator. * There are two variants for NewArray: @@ -103,6 +105,7 @@ public NewArray(Expression[] arguments, TypeReference typeRef, assert dimensions > 0; } + @Nonnull public SourceElement getLastElement() { if (arrayInitializer != null) { return arrayInitializer; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NotEquals.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NotEquals.java index a54e4856bd0..26de8570138 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NotEquals.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/NotEquals.java @@ -13,23 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Not equals. - */ +import javax.annotation.Nonnull; +import java.util.List; public class NotEquals extends ComparativeOperator { - + public NotEquals(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Not equals. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Not equals. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ public NotEquals(ExtList children) { @@ -38,20 +42,23 @@ public NotEquals(ExtList children) { /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { return 6; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnNotEquals(this); + v.performActionOnNotEquals(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Plus.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Plus.java index c04295e563d..277045e84f3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Plus.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Plus.java @@ -13,39 +13,47 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Addition or string concatenation operator "+". + * Addition or string concatenation operator "+". */ public class Plus extends BinaryOperator { - + public Plus(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public Plus(ExtList children) { - super(children); + super(children); } public Plus(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -53,20 +61,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPlus(this); + v.performActionOnPlus(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PlusAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PlusAssignment.java index 55bbabea684..103a28ed8d8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PlusAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PlusAssignment.java @@ -13,34 +13,42 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Addition or string concatenation assignment "+=". + * Addition or string concatenation assignment "+=". */ public class PlusAssignment extends Assignment { - + public PlusAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Plus assignment. - * @param children an ExtList with all children of this node - * the first children in list will be the one on the left - * side, the second the one on the right side. + * Plus assignment. + * + * @param children an ExtList with all children of this node + * the first children in list will be the one on the left + * side, the second the one on the right side. */ - public PlusAssignment(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -48,8 +56,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -57,20 +66,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPlusAssignment(this); + v.performActionOnPlusAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Positive.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Positive.java index 683256eabd6..4ab26a9a931 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Positive.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Positive.java @@ -13,42 +13,45 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Positive. - */ +import javax.annotation.Nonnull; +import java.util.List; -public class Positive extends Operator { +public class Positive extends Operator { + public Positive(PositionInfo pi, List comments, @Nonnull Expression child) { + super(pi, comments, new ImmutableArray<>(child)); + } /** - * Positive. - * @param expr the Expression + * Positive. + * + * @param expr the Expression */ - public Positive(Expression expr) { - super(expr); + public Positive(@Nonnull Expression expr) { + this(null, null, expr); } /** - * Positive. - * @param children an ExtList with all children of this node + * Positive. + * + * @param children an ExtList with all children of this node */ public Positive(ExtList children) { super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -56,8 +59,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -65,8 +69,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -74,22 +79,25 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Ordinary - * unary operators are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Ordinary + * unary operators are right associative. + * + * @return true, if the operator is left associative, + * false otherwise. */ public boolean isLeftAssociative() { return false; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPositive(this); + v.performActionOnPositive(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -97,8 +105,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - return services.getTypeConverter(). - getPromotedType(getExpressionAt(0).getKeYJavaType(services, ec)); + return services.getTypeConverter(). + getPromotedType(getExpressionAt(0).getKeYJavaType(services, ec)); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostDecrement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostDecrement.java index b5e02563e76..f3a795dc13e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostDecrement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostDecrement.java @@ -13,22 +13,26 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Post decrement. - */ +import javax.annotation.Nonnull; +import java.util.List; public class PostDecrement extends Assignment { - + public PostDecrement(PositionInfo pi, List comments, @Nonnull Expression lhs) { + super(pi, comments, lhs); + } /** - * Post decrement. - * @param children an ExtList with all children of this node + * Post decrement. + * + * @param children an ExtList with all children of this node */ public PostDecrement(ExtList children) { @@ -37,8 +41,9 @@ public PostDecrement(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -46,8 +51,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -55,20 +61,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return POSTFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPostDecrement(this); + v.performActionOnPostDecrement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostIncrement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostIncrement.java index ebd85062ec3..fb1f9b6dbf0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostIncrement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PostIncrement.java @@ -13,23 +13,30 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Post increment. + * Post increment. */ public class PostIncrement extends Assignment { - + public PostIncrement(PositionInfo pi, List comments, @Nonnull Expression lhs) { + super(pi, comments, lhs); + } /** - * Post increment. - * @param unary the Expression to be incremented by one + * Post increment. + * + * @param unary the Expression to be incremented by one */ public PostIncrement(Expression unary) { @@ -38,8 +45,9 @@ public PostIncrement(Expression unary) { /** - * Post increment. - * @param children an ExtList with all children of this node + * Post increment. + * + * @param children an ExtList with all children of this node */ public PostIncrement(ExtList children) { @@ -48,8 +56,9 @@ public PostIncrement(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -57,8 +66,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -66,20 +76,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return POSTFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPostIncrement(this); + v.performActionOnPostIncrement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreDecrement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreDecrement.java index d39e0f85889..a1f550a6ef1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreDecrement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreDecrement.java @@ -13,31 +13,36 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Pre decrement. - */ +import javax.annotation.Nonnull; +import java.util.List; public class PreDecrement extends Assignment { - + public PreDecrement(PositionInfo pi, List comments, @Nonnull Expression lhs) { + super(pi, comments, lhs); + } /** - * Pre decrement. - * @param children an ExtList with all children of this node + * Pre decrement. + * + * @param children an ExtList with all children of this node */ - + public PreDecrement(ExtList children) { - super(children); + super(children); } - + /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -45,8 +50,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -54,20 +60,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return PREFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPreDecrement(this); + v.performActionOnPreDecrement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreIncrement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreIncrement.java index f15cfd585d8..ec5be6d95c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreIncrement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/PreIncrement.java @@ -13,22 +13,26 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Pre increment. - */ +import javax.annotation.Nonnull; +import java.util.List; public class PreIncrement extends Assignment { - + public PreIncrement(PositionInfo pi, List comments, @Nonnull Expression lhs) { + super(pi, comments, lhs); + } /** - * Pre increment. - * @param children an ExtList with all children of this node + * Pre increment. + * + * @param children an ExtList with all children of this node */ public PreIncrement(ExtList children) { @@ -37,17 +41,19 @@ public PreIncrement(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { return 1; } - + /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -55,20 +61,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return PREFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnPreIncrement(this); + v.performActionOnPreIncrement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeft.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeft.java index 503782ad808..f1e87dfec26 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeft.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeft.java @@ -13,34 +13,25 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Shift left. - * - */ - -public class ShiftLeft extends Operator { - - /** - * Shift left. - */ +import javax.annotation.Nonnull; +import java.util.List; - public ShiftLeft() {} +public class ShiftLeft extends BinaryOperator { + public ShiftLeft(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Shift left. - * @param lhs an expression. - * @param rhs an expression. + * Shift left. + * + * @param lhs an expression. + * @param rhs an expression. */ public ShiftLeft(Expression lhs, Expression rhs) { super(lhs, rhs); @@ -49,28 +40,21 @@ public ShiftLeft(Expression lhs, Expression rhs) { /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public ShiftLeft(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. - */ - - public int getArity() { - return 2; - } - - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -78,19 +62,22 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnShiftLeft(this); + v.performActionOnShiftLeft(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -99,8 +86,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc=javaServ.getTypeConverter(); - return tc.getPromotedType - (tc.getKeYJavaType((Expression)getChildAt(0), ec)); + final TypeConverter tc = javaServ.getTypeConverter(); + return tc.getPromotedType + (tc.getKeYJavaType((Expression) getChildAt(0), ec)); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeftAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeftAssignment.java index 9da79c2ec01..c9086274f50 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeftAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftLeftAssignment.java @@ -13,30 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Shift left assignment. - * - */ +import javax.annotation.Nonnull; +import java.util.List; public class ShiftLeftAssignment extends Assignment { + public ShiftLeftAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Shift left assignment. - */ - - public ShiftLeftAssignment() {} - - /** - * Shift left assignment. - * @param lhs an expression. - * @param rhs an expression. + * Shift left assignment. + * + * @param lhs an expression. + * @param rhs an expression. */ public ShiftLeftAssignment(Expression lhs, Expression rhs) { @@ -46,19 +43,21 @@ public ShiftLeftAssignment(Expression lhs, Expression rhs) { /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public ShiftLeftAssignment(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -66,8 +65,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -75,20 +75,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnShiftLeftAssignment(this); + v.performActionOnShiftLeftAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRight.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRight.java index d7a5606efc7..646146fa3d5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRight.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRight.java @@ -13,62 +13,48 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Shift right. - * @author AutoDoc - */ -public class ShiftRight extends Operator { +import javax.annotation.Nonnull; +import java.util.List; - /** - * Shift right. - */ - public ShiftRight() {} + +public class ShiftRight extends BinaryOperator { + public ShiftRight(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Shift right. - * @param lhs an expression. - * @param rhs an expression. + * Shift right. + * + * @param lhs an expression. + * @param rhs an expression. */ public ShiftRight(Expression lhs, Expression rhs) { - super(lhs, rhs); + super(lhs, rhs); } /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public ShiftRight(ExtList children) { - super(children); + super(children); } - /** - * Get arity. - * @return the int value. - */ - - public int getArity() { - return 2; - } - - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -76,20 +62,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnShiftRight(this); + v.performActionOnShiftRight(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -98,8 +87,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc = javaServ.getTypeConverter(); - return tc.getPromotedType - (tc.getKeYJavaType((Expression)getChildAt(0), ec)); + final TypeConverter tc = javaServ.getTypeConverter(); + return tc.getPromotedType + (tc.getKeYJavaType((Expression) getChildAt(0), ec)); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRightAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRightAssignment.java index f940ea35863..e9e8dd9778c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRightAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/ShiftRightAssignment.java @@ -13,49 +13,50 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; -/** - * Shift right assignment. - * @author AutoDoc - */ +import org.key_project.util.ExtList; -public class ShiftRightAssignment extends Assignment { +import javax.annotation.Nonnull; +import java.util.List; - /** - * Shift right assignment. - */ - public ShiftRightAssignment() {} +public class ShiftRightAssignment extends Assignment { + public ShiftRightAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Shift right assignment. - * @param lhs an expression. - * @param rhs an expression. + * Shift right assignment. + * + * @param lhs an expression. + * @param rhs an expression. */ public ShiftRightAssignment(Expression lhs, Expression rhs) { super(lhs, rhs); } - /** + /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public ShiftRightAssignment(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -63,8 +64,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -72,20 +74,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnShiftRightAssignment(this); + v.performActionOnShiftRightAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Times.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Times.java index 7125dc33f8a..29e3a515551 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Times.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/Times.java @@ -13,12 +13,17 @@ package de.uka.ilkd.key.java.expression.operator; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import org.key_project.util.ExtList; import de.uka.ilkd.key.java.Expression; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; + /** * Times. * @author AutoDoc @@ -26,6 +31,10 @@ public class Times extends BinaryOperator { + public Times(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } + /** * Times. * @param lhs an expression. diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TimesAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TimesAssignment.java index fd5f29ce34d..74ae6d1b9da 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TimesAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TimesAssignment.java @@ -13,51 +13,49 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Times assignment. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; public class TimesAssignment extends Assignment { + public TimesAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Times assignment. - */ - - public TimesAssignment() {} - - /** - * Times assignment. - * @param lhs an expression. - * @param rhs an expression. + * Times assignment. + * + * @param lhs an expression. + * @param rhs an expression. */ - public TimesAssignment(Expression lhs, Expression rhs) { super(lhs, rhs); } - /** + /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public TimesAssignment(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -65,8 +63,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -74,20 +73,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnTimesAssignment(this); + v.performActionOnTimesAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeOperator.java index b7b9a3a3a1d..97b3c6e0a6d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeOperator.java @@ -13,8 +13,7 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.Services; @@ -23,64 +22,80 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; + /** - * Type operator. - * @author AutoDoc + * Type operator. + * + * @author AutoDoc */ public abstract class TypeOperator extends Operator implements TypeReferenceContainer { /** - * Type reference. + * Type reference. */ + @Nonnull protected final TypeReference typeReference; + public TypeOperator(PositionInfo pi, List comments, @Nonnull ImmutableArray children, + TypeReference typeReference) { + super(pi, comments, children); + this.typeReference = typeReference; + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a TypeReference (the referred type) - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments + * May contain: + * a TypeReference (the referred type) + * 2 of Expression (the first Expression as left hand + * side, the second as right hand side), + * Comments */ public TypeOperator(ExtList children) { - super(children); - typeReference=children.get(TypeReference.class); + super(children); + typeReference = children.get(TypeReference.class); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a TypeReference (the referred type) - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments + * May contain: + * a TypeReference (the referred type) + * 2 of Expression (the first Expression as left hand + * side, the second as right hand side), + * Comments */ public TypeOperator(ExtList children, PositionInfo pi) { - super(children); - typeReference=children.get(TypeReference.class); + super(children); + typeReference = children.get(TypeReference.class); } - + public TypeOperator(Expression unaryChild, TypeReference typeref) { super(unaryChild); - typeReference=typeref; + typeReference = typeref; } public TypeOperator(Expression[] arguments, TypeReference typeref) { super(arguments); - typeReference=typeref; + typeReference = typeref; } - public TypeOperator(){ - typeReference=null; + public TypeOperator() { + typeReference = null; } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ public int getTypeReferenceCount() { return (typeReference != null) ? 1 : 0; @@ -103,22 +118,22 @@ public TypeReference getTypeReferenceAt(int index) { } /** - * Get type reference. - * @return the type reference. + * Get type reference. + * + * @return the type reference. */ public TypeReference getTypeReference() { return typeReference; } - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return getKeYJavaType(javaServ); + public KeYJavaType getKeYJavaType(Services javaServ, + ExecutionContext ec) { + return getKeYJavaType(javaServ); } public KeYJavaType getKeYJavaType(Services javaServ) { - return getTypeReference().getKeYJavaType(); + return getTypeReference().getKeYJavaType(); } - } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRight.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRight.java index 76853ef2abd..865853688f7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRight.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRight.java @@ -13,34 +13,26 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Unsigned shift right. - * - */ - -public class UnsignedShiftRight extends Operator { - - /** - * Unsigned shift right. - */ +import javax.annotation.Nonnull; +import java.util.List; - public UnsignedShiftRight() {} +public class UnsignedShiftRight extends BinaryOperator { + public UnsignedShiftRight(PositionInfo pi, List comments, @Nonnull Expression lhs, + @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Unsigned shift right. - * @param lhs an expression. - * @param rhs an expression. + * Unsigned shift right. + * + * @param lhs an expression. + * @param rhs an expression. */ public UnsignedShiftRight(Expression lhs, Expression rhs) { @@ -50,28 +42,21 @@ public UnsignedShiftRight(Expression lhs, Expression rhs) { /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public UnsignedShiftRight(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. - */ - - public int getArity() { - return 2; - } - - /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -79,20 +64,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnUnsignedShiftRight(this); + v.performActionOnUnsignedShiftRight(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -101,8 +89,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - final TypeConverter tc=javaServ.getTypeConverter(); - return tc.getPromotedType - (tc.getKeYJavaType((Expression)getChildAt(0), ec)); + final TypeConverter tc = javaServ.getTypeConverter(); + return tc.getPromotedType + (tc.getKeYJavaType((Expression) getChildAt(0), ec)); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRightAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRightAssignment.java index 1f2a32312f5..a536153e08a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRightAssignment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/UnsignedShiftRightAssignment.java @@ -13,30 +13,27 @@ package de.uka.ilkd.key.java.expression.operator; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.Assignment; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Unsigned shift right assignment. - * - */ +import javax.annotation.Nonnull; +import java.util.List; public class UnsignedShiftRightAssignment extends Assignment { + public UnsignedShiftRightAssignment(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } /** - * Unsigned shift right assignment. - */ - - public UnsignedShiftRightAssignment() {} - - /** - * Unsigned shift right assignment. - * @param lhs an expression. - * @param rhs an expression. + * Unsigned shift right assignment. + * + * @param lhs an expression. + * @param rhs an expression. */ public UnsignedShiftRightAssignment(Expression lhs, Expression rhs) { @@ -47,18 +44,20 @@ public UnsignedShiftRightAssignment(Expression lhs, Expression rhs) { /** * Constructor for the transformation of COMPOST ASTs to KeY. * The first occurrence of an Expression in the given list is taken as - * the left hand side + * the left hand side * of the expression, the second occurrence is taken as the right hand * side of the expression. + * * @param children the children of this AST element as KeY classes. */ public UnsignedShiftRightAssignment(ExtList children) { - super(children); + super(children); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -66,8 +65,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -75,20 +75,23 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { return INFIX; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnUnsignedShiftRightAssignment(this); + v.performActionOnUnsignedShiftRightAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqConcat.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqConcat.java index 27052317595..e23763c8336 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqConcat.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqConcat.java @@ -13,14 +13,21 @@ package de.uka.ilkd.key.java.expression.operator.adt; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.operator.BinaryOperator; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; public class SeqConcat extends BinaryOperator { + public SeqConcat(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public SeqConcat(ExtList children) { super(children); @@ -43,10 +50,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnSeqConcat(this); + v.performActionOnSeqConcat(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSeqConcat(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetMinus.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetMinus.java index 8852773251a..2305de105ee 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetMinus.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetMinus.java @@ -13,13 +13,21 @@ package de.uka.ilkd.key.java.expression.operator.adt; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.operator.BinaryOperator; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; public class SetMinus extends BinaryOperator { + public SetMinus(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public SetMinus(ExtList children) { super(children); @@ -37,10 +45,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnSetMinus(this); + v.performActionOnSetMinus(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSetMinus(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetUnion.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetUnion.java index c6d629ba506..a32cc68d151 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetUnion.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SetUnion.java @@ -13,13 +13,21 @@ package de.uka.ilkd.key.java.expression.operator.adt; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.expression.operator.BinaryOperator; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; public class SetUnion extends BinaryOperator { + public SetUnion(PositionInfo pi, List comments, @Nonnull Expression lhs, @Nonnull Expression rhs) { + super(pi, comments, lhs, rhs); + } public SetUnion(ExtList children) { super(children); @@ -37,10 +45,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnSetUnion(this); + v.performActionOnSetUnion(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSetUnion(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayLengthReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayLengthReference.java index 0ae170b4037..30406e76b29 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayLengthReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayLengthReference.java @@ -13,112 +13,118 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaInfo; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.abstraction.PrimitiveType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Array length reference. As a length reference is int-valued, - * and hence it is no valid prefix. - * Do not instantiate this class if you want to construct the - * Java expression a.length! - * Use {@link JavaInfo#getArrayLength()} instead. + * Array length reference. As a length reference is int-valued, + * and hence it is no valid prefix. + * Do not instantiate this class if you want to construct the + * Java expression a.length! + * Use {@link JavaInfo#getArrayLength()} instead. + *

+ * TODO weigl: This class/javadoc looks strange! Please revise. */ public class ArrayLengthReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferenceSuffix { - - + implements Reference, Expression, ReferenceSuffix { /** - * Reference prefix. It must evaluate to an ArrayType. + * Reference prefix. It must evaluate to an ArrayType. */ protected final ReferencePrefix prefix; - /** - * Array length reference. - */ - public ArrayLengthReference() { - prefix = null; + public ArrayLengthReference(PositionInfo pi, List comments, ReferencePrefix prefix) { + super(pi, comments); + this.prefix = prefix; } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a ReferencePrefix (for the array length), - * Comments - */ + * May contain: + * a ReferencePrefix (for the array length), + * Comments + */ public ArrayLengthReference(ExtList children) { - super(children); - prefix = children.get(ReferencePrefix.class); + super(children); + prefix = children.get(ReferencePrefix.class); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { - return (prefix != null) ? 1 : 0; + return (prefix != null) ? 1 : 0; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null && index == 0) return prefix; throw new ArrayIndexOutOfBoundsException(); } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_INT); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_INT); } - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return getKeYJavaType(javaServ); + @Override + public KeYJavaType getKeYJavaType(Services javaServ, + ExecutionContext ec) { + return getKeYJavaType(javaServ); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ public ReferencePrefix getReferencePrefix() { return prefix; } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? this : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? this : prefix.getFirstElementIncludingBlocks(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnArrayLengthReference(this); + v.performActionOnArrayLengthReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printArrayLengthReference(this); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayReference.java index f4b6ea714bb..71fb8e6098c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ArrayReference.java @@ -13,121 +13,103 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.declaration.ArrayDeclaration; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Array reference. - * @author AutoDoc - */ +import javax.annotation.Nonnull; +import java.util.List; -public class ArrayReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, ReferenceSuffix, - ExpressionContainer, TypeReferenceContainer { +public final class ArrayReference extends JavaNonTerminalProgramElement + implements Reference, Expression, ReferencePrefix, ReferenceSuffix, + ExpressionContainer, TypeReferenceContainer { - /** - * Access path. - */ - protected final ReferencePrefix prefix; - + private final ReferencePrefix prefix; + private final ImmutableArray inits; - /** - Inits. - */ - protected final ImmutableArray inits; - - - /** - * Array reference. - */ - public ArrayReference() { - prefix = null; - this.inits=null; + public ArrayReference(PositionInfo pi, List comments, ReferencePrefix prefix, + ImmutableArray inits) { + super(pi, comments); + this.prefix = prefix; + this.inits = inits; } /** - * Array reference. - * @param accessPath a reference prefix. - * @param initializers an expression array. + * Array reference. + * + * @param accessPath a reference prefix. + * @param initializers an expression array. */ - public ArrayReference(ReferencePrefix accessPath, - Expression[] initializers) { - this.prefix = accessPath; - this.inits = new ImmutableArray(initializers); + public ArrayReference(ReferencePrefix accessPath, Expression[] initializers) { + this(null, null, accessPath, new ImmutableArray<>(initializers)); } /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * May contain: - * several of Expression (as initializers of the array), - * Comments. - * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because - * Expression and ReferencePrefix might not be disjunct. - * @param accessPath a ReferencePrefix of the array reference. - */ + * + * @param children the children of this AST element as KeY classes. + * May contain: + * several of Expression (as initializers of the array), + * Comments. + * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because + * Expression and ReferencePrefix might not be disjunct. + * @param accessPath a ReferencePrefix of the array reference. + */ public ArrayReference(ExtList children, ReferencePrefix accessPath, PositionInfo pi) { - super(children, pi); - Expression[] e = children.collect(Expression.class); - if(e.length>1){ - Expression[] e1 = new Expression[e.length-1]; - System.arraycopy(e, 0, e1, 0, e1.length); - this.prefix=new ArrayReference(e1, accessPath); - e1= new Expression[1]; - e1[0]=e[e.length-1]; - this.inits=new ImmutableArray(e1); - }else{ - this.prefix=accessPath; - this.inits=new ImmutableArray(e); - } + super(children, pi); + Expression[] e = children.collect(Expression.class); + if (e.length > 1) { + Expression[] e1 = new Expression[e.length - 1]; + System.arraycopy(e, 0, e1, 0, e1.length); + this.prefix = new ArrayReference(e1, accessPath); + e1 = new Expression[1]; + e1[0] = e[e.length - 1]; + this.inits = new ImmutableArray<>(e1); + } else { + this.prefix = accessPath; + this.inits = new ImmutableArray<>(e); + } } /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * May contain: - * several of Expression (as initializers of the array), - * Comments. - * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because - * Expression and ReferencePrefix might not be disjunct. - * @param accessPath a ReferencePrefix of the array reference. - */ + * + * @param children the children of this AST element as KeY classes. + * May contain: + * several of Expression (as initializers of the array), + * Comments. + * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because + * Expression and ReferencePrefix might not be disjunct. + * @param accessPath a ReferencePrefix of the array reference. + */ public ArrayReference(ExtList children, ReferencePrefix accessPath) { - this(children, accessPath, - children.get(PositionInfo.class)); + this(children, accessPath, children.get(PositionInfo.class)); } private ArrayReference(Expression[] e, ReferencePrefix accessPath) { - Expression[] e1 = new Expression[e.length-1]; - if(e.length>1){ - System.arraycopy(e, 0, e1, 0, e1.length); - this.prefix=new ArrayReference(e1, accessPath); - e1[0]=e[e.length-1]; - this.inits=new ImmutableArray(e1); - }else{ - this.prefix=accessPath; - this.inits=new ImmutableArray(e); - } + super((PositionInfo) null, null); + Expression[] e1 = new Expression[e.length - 1]; + if (e.length > 1) { + System.arraycopy(e, 0, e1, 0, e1.length); + this.prefix = new ArrayReference(e1, accessPath); + e1[0] = e[e.length - 1]; + this.inits = new ImmutableArray<>(e1); + } else { + this.prefix = accessPath; + this.inits = new ImmutableArray<>(e); + } } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ + @Override public int getExpressionCount() { int c = 0; if (prefix instanceof Expression) c += 1; @@ -144,9 +126,10 @@ public int getExpressionCount() { of bounds. */ + @Override public Expression getExpressionAt(int index) { if (prefix instanceof Expression) { - if (index == 0) return (Expression)prefix; + if (index == 0) return (Expression) prefix; index--; } if (inits != null) { @@ -156,9 +139,11 @@ public Expression getExpressionAt(int index) { } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (prefix instanceof TypeReference) ? 1 : 0; } @@ -172,41 +157,48 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { int result = 0; if (prefix != null) result++; - if (inits != null) result += inits.size(); + if (inits != null) result += inits.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; @@ -219,42 +211,46 @@ public ProgramElement getChildAt(int index) { } /** - * Get dimension expressions. - * @return the expression array wrapper. + * Get dimension expressions. + * + * @return the expression array wrapper. */ public ImmutableArray getDimensionExpressions() { return inits; } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? this : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? this : prefix.getFirstElementIncludingBlocks(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnArrayReference(this); + v.performActionOnArrayReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printArrayReference(this); } - public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; - } - + @Override public KeYJavaType getKeYJavaType(Services services, ExecutionContext ec) { - final KeYJavaType arrayType = services.getTypeConverter(). - getKeYJavaType((Expression)getChildAt(0), ec); - return ((ArrayDeclaration)arrayType.getJavaType()). - getBaseType().getKeYJavaType(); + final KeYJavaType arrayType = services.getTypeConverter(). + getKeYJavaType((Expression) getChildAt(0), ec); + return ((ArrayDeclaration) arrayType.getJavaType()). + getBaseType().getKeYJavaType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ExecutionContext.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ExecutionContext.java index 669ddf0f64e..edad104abe3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ExecutionContext.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ExecutionContext.java @@ -13,24 +13,18 @@ package de.uka.ilkd.key.java.reference; +import de.uka.ilkd.key.java.*; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.IProgramMethod; +import java.util.List; + public class ExecutionContext extends JavaNonTerminalProgramElement implements IExecutionContext, Reference { - - /** - * the class context - */ protected final TypeReference classContext; - /** * the reference to the active object */ @@ -39,7 +33,15 @@ public class ExecutionContext /** * the currently active method */ - private IProgramMethod methodContext; + private final IProgramMethod methodContext; + + public ExecutionContext(PositionInfo pi, List comments, TypeReference classContext, + ReferencePrefix runtimeInstance, IProgramMethod methodContext) { + super(pi, comments); + this.classContext = classContext; + this.runtimeInstance = runtimeInstance; + this.methodContext = methodContext; + } /** * creates an execution context reference @@ -49,11 +51,8 @@ public class ExecutionContext * @param runtimeInstance a ReferencePrefix to the object that * is currently active/executed */ - public ExecutionContext(TypeReference classContext, - IProgramMethod methodContext, ReferencePrefix runtimeInstance) { - this.classContext = classContext; - this.methodContext = methodContext; - this.runtimeInstance = runtimeInstance; + public ExecutionContext(TypeReference classContext, IProgramMethod methodContext, ReferencePrefix runtimeInstance) { + this(null, null, classContext, runtimeInstance, methodContext); } /** @@ -62,6 +61,7 @@ public ExecutionContext(TypeReference classContext, * context */ public ExecutionContext(ExtList children) { + super(children); this.classContext = children.get(TypeReference.class); children.remove(this.classContext); this.methodContext = children.get(IProgramMethod.class); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/FieldReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/FieldReference.java index 7cd1960ef4b..a85a9db8381 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/FieldReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/FieldReference.java @@ -14,119 +14,124 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.ProgramVariable; +import org.key_project.util.ExtList; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; -public class FieldReference extends VariableReference - implements MemberReference, ReferenceSuffix, - TypeReferenceContainer, ExpressionContainer { - /** - * Reference prefix. - */ - protected ReferencePrefix prefix; - +public class FieldReference extends VariableReference + implements MemberReference, ReferenceSuffix, TypeReferenceContainer, ExpressionContainer { + + @Nullable + private final ReferencePrefix prefix; + + public FieldReference(PositionInfo pi, List comments, ProgramVariable variable, ReferencePrefix prefix) { + super(pi, comments, variable); + this.prefix = prefix; + } + + public FieldReference(ProgramVariable variable, PositionInfo pi, ReferencePrefix prefix) { + this(pi, null, variable, prefix); + } protected FieldReference() { - prefix = null; + this(null, null, null, null); } public FieldReference(ProgramVariable pv, ReferencePrefix prefix) { - super(pv); - initPrefix(pv, prefix); + this(null, null, pv, getPrefix(pv, prefix)); } - private void initPrefix(ProgramVariable pv, ReferencePrefix prefix) { + private static ReferencePrefix getPrefix(ProgramVariable pv, ReferencePrefix prefix) { if (prefix == null && !pv.isStatic() && pv.isMember()) { - this.prefix = new ThisReference(); + return new ThisReference(); } else { - this.prefix = prefix; + return prefix; } } public FieldReference(ExtList children, ReferencePrefix prefix) { super(children); - initPrefix(getProgramVariable(), prefix); + this.prefix = getPrefix(getProgramVariable(), prefix); } public FieldReference(ProgramVariable pv, ReferencePrefix prefix, PositionInfo pi) { - super(pv, pi); - initPrefix(pv, prefix); - + this(pi, null, pv, getPrefix(pv, prefix)); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; if (prefix != null) result++; - if (variable != null) result++; + if (getProgramVariable() != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; index--; } - if (variable != null) { - if (index == 0) return variable; + if (getProgramVariable() != null) { + if (index == 0) return getProgramVariable(); } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ - public ReferencePrefix getReferencePrefix() { + @Nullable + public final ReferencePrefix getReferencePrefix() { return prefix; } /* - * returns true if the reference prefix is an explicit or implicit + * returns true if the reference prefix is an explicit or implicit * this reference this field reference does not refer to a static field */ public boolean referencesOwnInstanceField() { return (prefix == null || prefix instanceof ThisReference) && - !getProgramVariable().isStatic(); + !getProgramVariable().isStatic(); } - + /** - * Set reference prefix. - * @author VK + * Set reference prefix. + * + * @author VK */ public ReferencePrefix setReferencePrefix(ReferencePrefix rp) { - return new FieldReference(variable,rp); + return new FieldReference(getProgramVariable(), rp); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ - public int getTypeReferenceCount() { return (prefix instanceof TypeReference) ? 1 : 0; } @@ -141,14 +146,15 @@ public int getTypeReferenceCount() { */ public TypeReference getTypeReferenceAt(int index) { if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { return (prefix instanceof Expression) ? 1 : 0; @@ -164,38 +170,44 @@ public int getExpressionCount() { */ public Expression getExpressionAt(int index) { if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + return (Expression) prefix; } throw new ArrayIndexOutOfBoundsException(); } + @Nonnull public SourceElement getFirstElement() { - return (prefix == null) ? variable : prefix.getFirstElement(); + return (prefix == null) ? getProgramVariable() : prefix.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? variable : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? getProgramVariable() : prefix.getFirstElementIncludingBlocks(); } - /** pretty print */ + /** + * pretty print + */ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printFieldReference(this); } - - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnFieldReference(this); + v.performActionOnFieldReference(this); } - - /** are there "dots" in the prefix? */ + + /** + * are there "dots" in the prefix? + */ public boolean isSingleDeref() { - return prefix.getReferencePrefix()==null; + return prefix.getReferencePrefix() == null; } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MetaClassReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MetaClassReference.java index b52add63ae0..e79fa25f154 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MetaClassReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MetaClassReference.java @@ -13,75 +13,70 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Meta class reference. - * + * Meta class reference. */ -public class MetaClassReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, ReferenceSuffix, - TypeReferenceContainer { +public final class MetaClassReference extends JavaNonTerminalProgramElement + implements Reference, Expression, ReferencePrefix, ReferenceSuffix, TypeReferenceContainer { - /** - * Type reference. - */ - protected final TypeReference typeReference; + private final TypeReference typeReference; - /** - * Meta class reference. - */ - public MetaClassReference() { - typeReference=null; + public MetaClassReference(PositionInfo pi, List comments, TypeReference typeReference) { + super(pi, comments); + this.typeReference = typeReference; } /** - * Meta class reference. - * @param reference a type reference. + * Meta class reference. + * + * @param reference a type reference. */ public MetaClassReference(TypeReference reference) { - typeReference=reference; + this(null, null, reference); } - + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a TypeReference (as reference for the meta class), - * Comments - */ + * May contain: + * a TypeReference (as reference for the meta class), + * Comments + */ public MetaClassReference(ExtList children) { - super(children); - typeReference=children.get(TypeReference.class); + super(children); + typeReference = children.get(TypeReference.class); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { - return (typeReference != null) ? 1 : 0; + return (typeReference != null) ? 1 : 0; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (typeReference != null) { if (index == 0) return typeReference; @@ -90,17 +85,21 @@ public ProgramElement getChildAt(int index) { } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return typeReference; } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (typeReference != null) ? 1 : 0; } @@ -114,6 +113,7 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (typeReference != null && index == 0) { return typeReference; @@ -122,43 +122,51 @@ public TypeReference getTypeReferenceAt(int index) { } /** - * Get type reference. - * @return the type reference. + * Get type reference. + * + * @return the type reference. */ public TypeReference getTypeReference() { return typeReference; } + @Override + @Nonnull public SourceElement getFirstElement() { return (typeReference == null) ? this : typeReference.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (typeReference == null) ? this : typeReference.getFirstElementIncludingBlocks(); + return (typeReference == null) ? this : typeReference.getFirstElementIncludingBlocks(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnMetaClassReference(this); + v.performActionOnMetaClassReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printMetaClassReference(this); } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } + @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - throw new IllegalStateException - ("Metaclass references are not supported by KeY as" + - "\'java.lang.Class\' is not part of the Java Card standard"); + throw new IllegalStateException + ("Metaclass references are not supported by KeY as" + + "\'java.lang.Class\' is not part of the Java Card standard"); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodReference.java index 0c623aa4ac4..85316b5b216 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodReference.java @@ -13,19 +13,7 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; -import org.key_project.util.collection.ImmutableList; -import org.key_project.util.collection.ImmutableSLList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.TypeConverter; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.ExpressionStatement; import de.uka.ilkd.key.java.recoderext.ImplicitFieldAdder; @@ -36,78 +24,77 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; import de.uka.ilkd.key.logic.op.SchemaVariable; import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; +import org.key_project.util.collection.ImmutableList; +import org.key_project.util.collection.ImmutableSLList; + +import javax.annotation.Nonnull; +import java.util.List; -/** - * Method reference. - * @author AutoDoc - */ public class MethodReference extends JavaNonTerminalProgramElement - implements MethodOrConstructorReference, - MemberReference, ReferencePrefix, - ReferenceSuffix, ExpressionStatement, - TypeReferenceContainer, NameReference { - - /** - Access path. - */ - protected final ReferencePrefix prefix; - + implements MethodOrConstructorReference, + MemberReference, ReferencePrefix, + ReferenceSuffix, ExpressionStatement, + TypeReferenceContainer, NameReference { + /** - * Name. + * Access path. */ + protected final ReferencePrefix prefix; protected final MethodName name; - - /** - * Arguments. - */ protected final ImmutableArray arguments; - - public MethodReference(ExtList args, MethodName n, - ReferencePrefix p, PositionInfo pos) { + + public MethodReference(PositionInfo pi, List comments, ReferencePrefix prefix, + MethodName name, ImmutableArray arguments) { + super(pi, comments); + this.prefix = prefix; + this.name = name; + this.arguments = arguments; + } + + public MethodReference(ExtList args, MethodName n, ReferencePrefix p, PositionInfo pos) { super(pos); this.prefix = p; name = n; Debug.assertTrue(name != null, "Tried to reference unnamed method."); - this.arguments = new ImmutableArray(args.collect(Expression.class)); + this.arguments = new ImmutableArray<>(args.collect(Expression.class)); + } + + public MethodReference(ImmutableArray args, MethodName n, ReferencePrefix p) { + this(null, null, p, n, args); + Debug.assertTrue(name != null, "Tried to reference unnamed method."); + checkArguments(); } - - public MethodReference(ImmutableArray args, MethodName n, - ReferencePrefix p) { + + public MethodReference(ImmutableArray args, MethodName n, + ReferencePrefix p, PositionInfo pos) { + super(pos); this.prefix = p; name = n; Debug.assertTrue(name != null, "Tried to reference unnamed method."); - this.arguments = args; - checkArguments(); - } - - public MethodReference(ImmutableArray args, MethodName n, - ReferencePrefix p, PositionInfo pos) { - super(pos); - this.prefix=p; - name = n; - Debug.assertTrue(name != null, "Tried to reference unnamed method."); - this.arguments=args; - checkArguments(); + this.arguments = args; + checkArguments(); } - public MethodReference(ExtList children, MethodName n, ReferencePrefix p) { - this(new ImmutableArray(children.collect(Expression.class)), - n, p, children.get(PositionInfo.class)); + public MethodReference(ExtList children, MethodName n, ReferencePrefix p) { + this(new ImmutableArray<>(children.collect(Expression.class)), + n, p, children.get(PositionInfo.class)); } - public MethodReference(ExtList children, MethodName n, ReferencePrefix p,PositionInfo pos, String scope) { - this(new ImmutableArray(children.collect(Expression.class)), - n, p, pos); + public MethodReference(ExtList children, MethodName n, ReferencePrefix p, PositionInfo pos, String scope) { + this(new ImmutableArray<>(children.collect(Expression.class)), n, p, pos); } - protected void checkArguments(){ - ImmutableArray args = getArguments(); - for(Expression arg:args){ - if(arg==null) - throw new NullPointerException(); - } + protected void checkArguments() { + ImmutableArray args = getArguments(); + for (Expression arg : args) { + if (arg == null) + throw new NullPointerException(); + } } - + + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? getChildAt(0).getFirstElement() : prefix.getFirstElement(); } @@ -119,34 +106,37 @@ public SourceElement getFirstElementIncludingBlocks() { /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ @Override public ReferencePrefix getReferencePrefix() { return prefix; } - + /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; - if (prefix != null) result++; - if (name != null) result++; - if (arguments != null) result += arguments.size(); + if (prefix != null) result++; + if (name != null) result++; + if (arguments != null) result += arguments.size(); return result; } - + /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { @@ -158,20 +148,20 @@ public ProgramElement getChildAt(int index) { index--; } if (arguments != null) { - return arguments.get(index); + return arguments.get(index); } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ public int getTypeReferenceCount() { return (prefix instanceof TypeReference) ? 1 : 0; } - - + /* Return the type reference at the specified index in this node's @@ -183,15 +173,16 @@ public int getTypeReferenceCount() { */ public TypeReference getTypeReferenceAt(int index) { if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { int result = 0; @@ -213,7 +204,7 @@ public int getExpressionCount() { public Expression getExpressionAt(int index) { if (prefix instanceof Expression) { if (index == 0) { - return (Expression)prefix; + return (Expression) prefix; } index -= 1; } @@ -224,28 +215,31 @@ public Expression getExpressionAt(int index) { } /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ public final String getName() { return (name == null) ? null : name.toString(); } /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public ProgramElementName getProgramElementName() { - if (name instanceof ProgramElementName) { - return (ProgramElementName) name; - } else if (name instanceof SchemaVariable) { - return (((ProgramSV)name).getProgramElementName()); - } else return null; + if (name instanceof ProgramElementName) { + return (ProgramElementName) name; + } else if (name instanceof SchemaVariable) { + return (((ProgramSV) name).getProgramElementName()); + } else return null; } /** - * Get arguments. - * @return the expression array wrapper. + * Get arguments. + * + * @return the expression array wrapper. */ @Override public ImmutableArray getArguments() { @@ -253,8 +247,9 @@ public ImmutableArray getArguments() { } /** - * Gets index-th argument - * @return the expression + * Gets index-th argument + * + * @return the expression */ public Expression getArgumentAt(int index) { if (arguments != null) { @@ -268,50 +263,50 @@ public Expression getArgumentAt(int index) { * method */ public ImmutableList getMethodSignature(Services services, - ExecutionContext ec) { - ImmutableList signature = ImmutableSLList.nil(); - if (arguments != null) { + ExecutionContext ec) { + ImmutableList signature = ImmutableSLList.nil(); + if (arguments != null) { final TypeConverter typeConverter = services.getTypeConverter(); - for (int i = arguments.size()-1; i>=0; i--) { + for (int i = arguments.size() - 1; i >= 0; i--) { signature = signature.prepend - (typeConverter.getKeYJavaType(getArgumentAt(i), ec)); - } - } - return signature; + (typeConverter.getKeYJavaType(getArgumentAt(i), ec)); + } + } + return signature; } - + /** * returns the static KeYJavaType of the methods prefix */ - public KeYJavaType determineStaticPrefixType(Services services, + public KeYJavaType determineStaticPrefixType(Services services, ExecutionContext ec) { - KeYJavaType prefixType; + KeYJavaType prefixType; if (prefix == null) { - prefixType = ec.getTypeReference().getKeYJavaType(); - } else { - if (prefix instanceof Expression) { - prefixType = ((Expression)prefix).getKeYJavaType(services, ec); - } else { - prefixType = ((TypeReference)prefix).getKeYJavaType(); - } - } - return prefixType; + prefixType = ec.getTypeReference().getKeYJavaType(); + } else { + if (prefix instanceof Expression) { + prefixType = ((Expression) prefix).getKeYJavaType(services, ec); + } else { + prefixType = ((TypeReference) prefix).getKeYJavaType(); + } + } + return prefixType; } - - public IProgramMethod method(Services services, - KeYJavaType refPrefixType, - ExecutionContext ec) { + + public IProgramMethod method(Services services, + KeYJavaType refPrefixType, + ExecutionContext ec) { ProgramVariable inst = services.getJavaInfo().getAttribute( ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS, ec.getTypeReference().getKeYJavaType()); - IProgramMethod pm = method(services, refPrefixType, + IProgramMethod pm = method(services, refPrefixType, getMethodSignature(services, ec), ec.getTypeReference().getKeYJavaType()); - while(inst!=null && pm==null){ + while (inst != null && pm == null) { KeYJavaType classType = inst.getKeYJavaType(); - pm = method(services, classType, + pm = method(services, classType, getMethodSignature(services, ec), classType); - if(pm!=null){ + if (pm != null) { return pm; } inst = services.getJavaInfo().getAttribute( @@ -319,65 +314,66 @@ public IProgramMethod method(Services services, } return pm; } - + /** - * - * @param services the Services class offering access to metamodel - * information - * @param classType the KeYJavaType where to start looking for the - * declared method + * @param services the Services class offering access to metamodel + * information + * @param classType the KeYJavaType where to start looking for the + * declared method * @param signature the IList of the arguments types - * @param context the KeYJavaType from where the method is called + * @param context the KeYJavaType from where the method is called * @return the found program method */ public IProgramMethod method - (Services services, KeYJavaType classType, - ImmutableList signature, - KeYJavaType context) { - final String methodName = name.toString(); - IProgramMethod pm = services.getJavaInfo().getProgramMethod(classType, + (Services services, KeYJavaType classType, + ImmutableList signature, + KeYJavaType context) { + final String methodName = name.toString(); + IProgramMethod pm = services.getJavaInfo().getProgramMethod(classType, methodName, signature, context); - return pm; + return pm; } - + public boolean implicit() { - return getProgramElementName().toString().charAt(0)=='<'; + return getProgramElementName().toString().charAt(0) == '<'; } public MethodName getMethodName() { - return name; + return name; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnMethodReference(this); + v.performActionOnMethodReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printMethodReference(this); } - public KeYJavaType getKeYJavaType(Services services, - ExecutionContext ec) { - IProgramMethod meth = method(services, - determineStaticPrefixType(services, ec), ec); - if(meth == null){ - return ec.getTypeReference().getKeYJavaType(); - } - return meth.getReturnType(); - + public KeYJavaType getKeYJavaType(Services services, + ExecutionContext ec) { + IProgramMethod meth = method(services, + determineStaticPrefixType(services, ec), ec); + if (meth == null) { + return ec.getTypeReference().getKeYJavaType(); + } + return meth.getReturnType(); + } - public KeYJavaType getKeYJavaType(Services javaServ) { - return getKeYJavaType(); + public KeYJavaType getKeYJavaType(Services javaServ) { + return getKeYJavaType(); } public KeYJavaType getKeYJavaType() { - Debug.fail(""); - return null; + Debug.fail(""); + return null; } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReference.java index 9f2f8f9a12b..3fd58f42155 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReference.java @@ -13,54 +13,66 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; /** - * Package reference. - * @author AutoDoc + * Package reference. + * + * @author AutoDoc */ public class PackageReference extends JavaNonTerminalProgramElement - implements TypeReferenceInfix, PackageReferenceContainer { + implements TypeReferenceInfix, PackageReferenceContainer { /** - * Prefix. + * Prefix. */ + @Nullable protected final ReferencePrefix prefix; /** - * Name. + * Name. */ + @Nonnull protected final ProgramElementName name; /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a ProgramElementName (as the name of the method reference), - * a ReferencePrefix (as accessPath to the package), - * Comments. + * May contain: + * a ProgramElementName (as the name of the method reference), + * a ReferencePrefix (as accessPath to the package), + * Comments. */ + @Deprecated public PackageReference(ExtList children) { - prefix=children.get(PackageReference.class); - name=children.get(ProgramElementName.class); - assert name != null; + super(children); + prefix = children.get(PackageReference.class); + name = children.get(ProgramElementName.class); + assert name != null; + } + + public PackageReference(PositionInfo pi, List comments, + @Nullable ReferencePrefix prefix, @Nonnull ProgramElementName name) { + super(pi, comments); + this.prefix = prefix; + this.name = name; } - public PackageReference(ProgramElementName name, - ReferencePrefix prefix) { - this.prefix = prefix; - this.name = name; - assert name != null; + public PackageReference(ProgramElementName name, @Nullable ReferencePrefix prefix) { + this(null, null, prefix, name); } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? name : prefix.getFirstElement(); } @@ -71,95 +83,105 @@ public SourceElement getFirstElementIncludingBlocks() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { int result = 0; if (prefix != null) result++; - if (name != null) result++; + result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; index--; } - if (name != null) { - if (index == 0) return name; - } + if (index == 0) return name; throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Get the package reference. - * @return the package reference. + * Get the package reference. + * + * @return the package reference. */ + @Override public PackageReference getPackageReference() { - return (prefix instanceof PackageReference) - ? (PackageReference)prefix : null; + return (prefix instanceof PackageReference) + ? (PackageReference) prefix : null; } /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ + @Override public final String getName() { - return (name == null) ? null : name.toString(); + return name.toString(); } /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ + @Override public ProgramElementName getProgramElementName() { return name; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnPackageReference(this); + v.performActionOnPackageReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printPackageReference(this); } - public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; - } - public boolean equals(Object o) { - if (!(o instanceof PackageReference)) { - return false; - } - final PackageReference pr = (PackageReference) o; - return pr.name.equals(name) - && (pr.prefix == null && prefix == null - || pr.prefix != null - && prefix != null - && pr.prefix.equals(prefix)); + if (!(o instanceof PackageReference)) { + return false; + } + final PackageReference pr = (PackageReference) o; + return pr.name.equals(name) + && (pr.prefix == null && prefix == null + || pr.prefix != null + && prefix != null + && pr.prefix.equals(prefix)); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchematicFieldReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchematicFieldReference.java index 17cbb2639ec..107fe26c0ef 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchematicFieldReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchematicFieldReference.java @@ -13,177 +13,177 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceData; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; import de.uka.ilkd.key.logic.op.ProgramSV; +import de.uka.ilkd.key.logic.op.ProgramVariable; import de.uka.ilkd.key.logic.op.SchemaVariable; import de.uka.ilkd.key.rule.MatchConditions; -import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; -/** - * Field reference. - * @author AutoDoc - */ -public class SchematicFieldReference extends FieldReference - implements MemberReference, ReferenceSuffix, - TypeReferenceContainer, ExpressionContainer { +public class SchematicFieldReference extends FieldReference + implements MemberReference, ReferenceSuffix, TypeReferenceContainer, ExpressionContainer { /** * Reference suffix */ - protected final SchemaVariable schemaVariable; + protected final SchemaVariable schemaVariable; + public SchematicFieldReference(PositionInfo pi, List comments, ProgramVariable variable, + ReferencePrefix prefix, SchemaVariable schemaVariable) { + super(pi, comments, variable, prefix); + this.schemaVariable = schemaVariable; + } public SchematicFieldReference(SchemaVariable pe, ReferencePrefix prefix) { - this.schemaVariable = pe; - this.prefix = prefix; + this(null, null, null, prefix, pe); } public SchematicFieldReference(ExtList children, ReferencePrefix prefix) { - this.schemaVariable = children.get(SchemaVariable.class); - this.prefix = prefix; + super(children, prefix); + this.schemaVariable = children.get(SchemaVariable.class); } /** * Returns the number of children of this node. + * * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; - if (prefix != null) result++; + if (getReferencePrefix() != null) result++; if (schemaVariable != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (prefix != null) { - if (index == 0) return prefix; + if (getReferencePrefix() != null) { + if (index == 0) return getReferencePrefix(); index--; } if (schemaVariable != null) { - if (index == 0) return (ProgramSV)schemaVariable; + if (index == 0) return (ProgramSV) schemaVariable; } throw new ArrayIndexOutOfBoundsException(); } - /** - * Get reference prefix. - * @return the reference prefix. - */ - public ReferencePrefix getReferencePrefix() { - return prefix; - } /** * Get reference prefix. + * * @return the reference prefix. */ public ReferenceSuffix getReferenceSuffix() { - return (ProgramSV)schemaVariable; + return (ProgramSV) schemaVariable; } /** - * Set reference prefix. - * @author VK + * Set reference prefix. + * + * @author VK */ public ReferencePrefix setReferencePrefix(ReferencePrefix rp) { - return new SchematicFieldReference(schemaVariable, rp); + return new SchematicFieldReference(schemaVariable, rp); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ public int getTypeReferenceCount() { - return (prefix instanceof TypeReference) ? 1 : 0; + return (getReferencePrefix() instanceof TypeReference) ? 1 : 0; } /** * Return the type reference at the specified index in this node's * "virtual" type reference array. + * * @param index an index for a type reference. * @return the type reference with the given index. - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. */ public TypeReference getTypeReferenceAt(int index) { - if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + if (getReferencePrefix() instanceof TypeReference && index == 0) { + return (TypeReference) getReferencePrefix(); } throw new ArrayIndexOutOfBoundsException(); } /** * Get the number of expressions in this container. + * * @return the number of expressions. */ public int getExpressionCount() { - return (prefix instanceof Expression) ? 1 : 0; + return (getReferencePrefix() instanceof Expression) ? 1 : 0; } /** - * Return the expression at the specified index in this node's - * "virtual" expression array. - * @param index an index for an expression. - * @return the expression with the given index. - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds. + * Return the expression at the specified index in this node's + * "virtual" expression array. + * + * @param index an index for an expression. + * @return the expression with the given index. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. */ public Expression getExpressionAt(int index) { - if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + if (getReferencePrefix() instanceof Expression && index == 0) { + return (Expression) getReferencePrefix(); } throw new ArrayIndexOutOfBoundsException(); } + @Nonnull public SourceElement getFirstElement() { - return (prefix == null) ? (ProgramSV)schemaVariable : prefix.getFirstElement(); + return (getReferencePrefix() == null) ? (ProgramSV) schemaVariable : getReferencePrefix().getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? (ProgramSV)schemaVariable : prefix.getFirstElementIncludingBlocks(); + return (getReferencePrefix() == null) ? (ProgramSV) schemaVariable : + getReferencePrefix().getFirstElementIncludingBlocks(); } public ProgramElementName getProgramElementName() { - return (ProgramElementName) schemaVariable.name(); + return (ProgramElementName) schemaVariable.name(); } - /** - * pretty print + /** + * pretty print */ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printFieldReference(this); } - /** + /** * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnSchematicFieldReference(this); + v.performActionOnSchematicFieldReference(this); } @@ -191,19 +191,19 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { ProgramElement src = source.getSource(); if (!(src instanceof FieldReference)) { LOGGER.debug("Program match failed. SchematicFieldReferences matches " + - "only FieldReferences (pattern {}, source {})", this, src); + "only FieldReferences (pattern {}, source {})", this, src); return null; } - + final SourceData newSource = new SourceData(src, 0, source.getServices()); - + matchCond = super.matchChildren(newSource, matchCond, 0); - + if (matchCond == null) { return null; } source.next(); return matchCond; } - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SpecialConstructorReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SpecialConstructorReference.java index 4191fc7def6..99ec43d18e9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SpecialConstructorReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SpecialConstructorReference.java @@ -13,108 +13,113 @@ package de.uka.ilkd.key.java.reference; +import de.uka.ilkd.key.java.*; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.ProgramElement; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; /** - * Occurs in a constructor declaration as the first statement - * as this(...) or super(...) reference. - * The Reference knows the constructor declaration it refers to. + * Occurs in a constructor declaration as the first statement + * as this(...) or super(...) reference. + * The Reference knows the constructor declaration it refers to. */ public abstract class SpecialConstructorReference - extends JavaNonTerminalProgramElement implements ConstructorReference { - - + extends JavaNonTerminalProgramElement implements ConstructorReference { + @Nonnull protected final ImmutableArray arguments; - + public SpecialConstructorReference(PositionInfo pi, List comments, + @Nullable ImmutableArray arguments) { + super(pi, comments); + this.arguments = arguments == null ? new ImmutableArray<>() : arguments; + } public SpecialConstructorReference() { - this.arguments = null; + this(null, null, null); } /** * Special constructor reference. + * * @param arguments an expression mutable list. */ public SpecialConstructorReference(Expression[] arguments) { - this.arguments = new ImmutableArray(arguments); + this(null, null, new ImmutableArray<>(arguments)); } /** * Special constructor reference. + * * @param arguments an expression mutable list. */ - public SpecialConstructorReference(ImmutableArray arguments) { - this.arguments = arguments; + public SpecialConstructorReference(@Nullable ImmutableArray arguments) { + this(null, null, arguments); } - + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * several of Expression (as initializers of the array), - * Comments - */ + * May contain: + * several of Expression (as initializers of the array), + * Comments + */ public SpecialConstructorReference(ExtList children) { - super(children); - this.arguments = new ImmutableArray - (children.collect(Expression.class)); + super(children); + this.arguments = new ImmutableArray<>(children.collect(Expression.class)); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * several of Expression (as initializers of the array), - * Comments - */ + * May contain: + * several of Expression (as initializers of the array), + * Comments + */ public SpecialConstructorReference(ExtList children, PositionInfo pi) { - super(children, pi); - this.arguments = new ImmutableArray - (children.collect(Expression.class)); + super(children, pi); + this.arguments = new ImmutableArray<>(children.collect(Expression.class)); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { return getExpressionCount(); } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (arguments != null) { - return arguments.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return arguments.get(index); } - + /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { - return (arguments != null) ? arguments.size() : 0; + return arguments.size(); } /* @@ -126,15 +131,13 @@ public int getExpressionCount() { of bounds. */ public Expression getExpressionAt(int index) { - if (arguments != null) { - return arguments.get(index); - } - throw new ArrayIndexOutOfBoundsException(); + return arguments.get(index); } /** - * Get arguments. - * @return the expression mutable list. + * Get arguments. + * + * @return the expression mutable list. */ public ImmutableArray getArguments() { return arguments; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperConstructorReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperConstructorReference.java index 4dec4240759..0ad3f709545 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperConstructorReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperConstructorReference.java @@ -22,6 +22,8 @@ import de.uka.ilkd.key.java.SourceElement; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * Super constructor reference. */ @@ -122,7 +124,8 @@ public ReferencePrefix getReferencePrefix() { } - @Override + @Nonnull + @Override public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperReference.java index 1bc9ce6751b..1111e621c1c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SuperReference.java @@ -13,59 +13,56 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Super reference. - * - */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; -public class SuperReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, - ReferenceSuffix, ExpressionContainer, - TypeReferenceContainer { +public class SuperReference extends JavaNonTerminalProgramElement implements Reference, Expression, ReferencePrefix, + ReferenceSuffix, ExpressionContainer, TypeReferenceContainer { /** - * Access path. + * Access path. */ + @Nullable private final ReferencePrefix prefix; - /** - * Super reference. - */ + public SuperReference(PositionInfo pi, List comments, ReferencePrefix prefix) { + super(pi, comments); + this.prefix = prefix; + } + public SuperReference() { - prefix = null; + this(null, null, null); } /** - * Super reference. - * @param accessPath a reference expression. + * Super reference. + * + * @param accessPath a reference expression. */ public SuperReference(ReferencePrefix accessPath) { - this.prefix = accessPath; + this(null, null, accessPath); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - */ + */ public SuperReference(ExtList children) { - prefix =children.get(ReferencePrefix.class); + super(children); + prefix = children.get(ReferencePrefix.class); } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } @@ -76,44 +73,52 @@ public SourceElement getFirstElementIncludingBlocks() { } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { - int count = 0; - if (prefix != null) count++; + int count = 0; + if (prefix != null) count++; return count; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; - } + } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ + @Override public int getExpressionCount() { return (prefix instanceof Expression) ? 1 : 0; } @@ -127,18 +132,21 @@ public int getExpressionCount() { of bounds. */ + @Override public Expression getExpressionAt(int index) { if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + return (Expression) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (prefix instanceof TypeReference) ? 1 : 0; } @@ -152,35 +160,37 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if ((prefix instanceof TypeReference) && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnSuperReference(this); + v.performActionOnSuperReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSuperReference(this); } - public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; - } - /** - * returns the KeYJavaType + * returns the KeYJavaType */ + @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getSuperclass - (ec.getTypeReference().getKeYJavaType()); + return javaServ.getJavaInfo().getSuperclass + (ec.getTypeReference().getKeYJavaType()); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisReference.java index 03bc6b6acd1..9b3481f3190 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisReference.java @@ -13,63 +13,64 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Reference; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; /** - * A reference to the current object. - * "this" can be prefixed by a type reference (to resolve ambiguities - * with inner classes). + * A reference to the current object. + * "this" can be prefixed by a type reference (to resolve ambiguities + * with inner classes). */ -public class ThisReference - extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, ReferenceSuffix, TypeReferenceContainer { - - /** - * Prefix. - */ - private final ReferencePrefix prefix; +public class ThisReference extends JavaNonTerminalProgramElement + implements Reference, Expression, ReferencePrefix, ReferenceSuffix, TypeReferenceContainer { + @Nullable + private final TypeReference prefix; + public ThisReference(PositionInfo pi, List comments, @Nullable TypeReference prefix) { + super(pi, comments); + this.prefix = prefix; + } /** - * This reference. + * This reference. */ public ThisReference() { - prefix = null; + this(null, null, null); } /** - * This reference. - * @param outer a type reference. + * This reference. + * + * @param outer a type reference. */ public ThisReference(TypeReference outer) { - prefix = outer; + this(null, null, outer); } - /** + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a TypeReference (as reference for the ThisReference) - * Comments - */ + * May contain: + * a TypeReference (as reference for the ThisReference) + * Comments + */ public ThisReference(ExtList children) { - super(children); - prefix = children.get(TypeReference.class); + super(children); + prefix = children.get(TypeReference.class); } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } @@ -80,23 +81,27 @@ public SourceElement getFirstElementIncludingBlocks() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { - int count = 0; - if (prefix != null) count++; + int count = 0; + if (prefix != null) count++; return count; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; @@ -105,17 +110,21 @@ public ProgramElement getChildAt(int index) { } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (prefix != null) ? 1 : 0; } @@ -129,32 +138,38 @@ public int getTypeReferenceCount() { of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnThisReference(this); + v.performActionOnThisReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printThisReference(this); } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; - } + return this; + } - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return ec.getTypeReference().getKeYJavaType(); + @Override + public KeYJavaType getKeYJavaType(Services javaServ, + ExecutionContext ec) { + return ec.getTypeReference().getKeYJavaType(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceImp.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceImp.java index d4d838b2f58..606703caab2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceImp.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceImp.java @@ -13,79 +13,68 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceData; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.abstraction.KeYJavaType; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; import de.uka.ilkd.key.rule.MatchConditions; -/** - * TypeReferences reference {@link recoder.abstraction.Type}s by name. - * A TypeReference can refer to an outer or inner type and hence can also - * be a {@link MemberReference}, but does not have to. - * A TypeReference can also occur as part of a reference path and - * as a prefix for types, too. As a possible suffix for types, it can - * have other TypeReferences as a prefix, playing the role of a - * {@link TypeReferenceContainer}. - */ - -public abstract class TypeReferenceImp - extends JavaNonTerminalProgramElement - implements TypeReference { +import org.key_project.util.ExtList; +import javax.annotation.Nonnull; +import java.util.List; - /** - * Prefix. - */ - protected ReferencePrefix prefix; +/** + * TypeReferences reference {@link recoder.abstraction.Type}s by name. + * A TypeReference can refer to an outer or inner type and hence can also + * be a {@link MemberReference}, but does not have to. + * A TypeReference can also occur as part of a reference path and + * as a prefix for types, too. As a possible suffix for types, it can + * have other TypeReferences as a prefix, playing the role of a + * {@link TypeReferenceContainer}. + */ - /** - * Dimensions. - */ - protected int dimensions; +public abstract class TypeReferenceImp extends JavaNonTerminalProgramElement implements TypeReference { - /** - * Name. - */ - protected ProgramElementName name; + protected final ReferencePrefix prefix; + protected final int dimensions; + protected final ProgramElementName name; + public TypeReferenceImp(PositionInfo pi, List comments, ReferencePrefix prefix, + int dimensions, ProgramElementName name) { + super(pi, comments); + this.prefix = prefix; + this.dimensions = dimensions; + this.name = name; + } /** * Constructor for the transformation of RECODER ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: - * a ReferencePrefix (as prefix of the type reference) - * a ProgramElementName (as name for the type reference) - * Comments - * @param dim the dimension of this type + * May contain: + * a ReferencePrefix (as prefix of the type reference) + * a ProgramElementName (as name for the type reference) + * Comments + * @param dim the dimension of this type */ public TypeReferenceImp(ExtList children, int dim) { - super(children); - prefix = children.get(ReferencePrefix.class); - name = children.get(ProgramElementName.class); - dimensions = dim; + super(children); + prefix = children.get(ReferencePrefix.class); + name = children.get(ProgramElementName.class); + dimensions = dim; } - public TypeReferenceImp(ProgramElementName name) { - this(name, 0, null); + public TypeReferenceImp(ProgramElementName name) { + this(name, 0, null); } - public TypeReferenceImp(ProgramElementName name, - int dimension, - ReferencePrefix prefix) { - this.name = name; - this.dimensions = dimension; - this.prefix = prefix; + public TypeReferenceImp(ProgramElementName name, int dimension, ReferencePrefix prefix) { + this(null, null, prefix, dimension, name); } + @Override + @Nonnull public SourceElement getFirstElement() { return (prefix == null) ? name : prefix.getFirstElement(); } @@ -96,24 +85,28 @@ public SourceElement getFirstElementIncludingBlocks() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { int result = 0; if (prefix != null) result++; - if (name != null) result++; + if (name != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (prefix != null) { if (index == 0) return prefix; @@ -126,9 +119,11 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of type references in this container. - * @return the number of type references. + * Get the number of type references in this container. + * + * @return the number of type references. */ + @Override public int getTypeReferenceCount() { return (prefix instanceof TypeReference) ? 1 : 0; } @@ -141,17 +136,20 @@ public int getTypeReferenceCount() { @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ + @Override public TypeReference getTypeReferenceAt(int index) { if (prefix instanceof TypeReference && index == 0) { - return (TypeReference)prefix; + return (TypeReference) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ + @Override public int getExpressionCount() { return (prefix instanceof Expression) ? 1 : 0; } @@ -164,77 +162,91 @@ public int getExpressionCount() { @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ + @Override public Expression getExpressionAt(int index) { if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + return (Expression) prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ + @Override public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Get the package reference. - * @return the package reference. + * Get the package reference. + * + * @return the package reference. */ + @Override public PackageReference getPackageReference() { - return (prefix instanceof PackageReference) - ? (PackageReference)prefix : null; + return (prefix instanceof PackageReference) + ? (PackageReference) prefix : null; } - + /** - * Get dimensions. - * @return the int value. + * Get dimensions. + * + * @return the int value. */ + @Override public int getDimensions() { return dimensions; } /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ + @Override public final String getName() { return (name == null) ? null : name.toString(); } - public abstract KeYJavaType getKeYJavaType(); - /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ + @Override public ProgramElementName getProgramElementName() { return name; } - - /** calls the corresponding method of a visitor in order to + + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnTypeReference(this); + v.performActionOnTypeReference(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printTypeReference(this); } + @Override public MatchConditions match(SourceData source, MatchConditions matchCond) { - final ProgramElement pe = source.getSource(); - if (!(pe instanceof TypeReference) || ((TypeReference)pe).getDimensions() != getDimensions()) { + final ProgramElement pe = source.getSource(); + if (!(pe instanceof TypeReference) || ((TypeReference) pe).getDimensions() != getDimensions()) { return null; - } - + } + return super.match(source, matchCond); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/VariableReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/VariableReference.java index fb8b8318e9f..62e44e4403e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/VariableReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/VariableReference.java @@ -13,30 +13,30 @@ package de.uka.ilkd.key.java.reference; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; import de.uka.ilkd.key.logic.op.ProgramVariable; +import org.key_project.util.ExtList; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; public class VariableReference extends JavaNonTerminalProgramElement - implements NameReference, Expression, - ReferencePrefix { + implements NameReference, Expression, ReferencePrefix { + @Nullable + private final ProgramVariable variable; - protected final ProgramVariable variable; + public VariableReference(PositionInfo pi, List comments, ProgramVariable variable) { + super(pi, comments); + this.variable = variable; + } protected VariableReference() { - variable = null; + this(null, null, null); } public VariableReference(ExtList children) { @@ -45,17 +45,17 @@ public VariableReference(ExtList children) { } public VariableReference(ProgramVariable variable, PositionInfo pi) { - super(pi); - this.variable = variable; + super(pi); + this.variable = variable; } public VariableReference(ProgramVariable variable) { - this(variable, PositionInfo.UNDEFINED); + this(variable, PositionInfo.UNDEFINED); } - public ProgramElementName getProgramElementName(){ - return (ProgramElementName) variable.name(); + public ProgramElementName getProgramElementName() { + return (ProgramElementName) variable.name(); } public int getChildCount() { @@ -65,10 +65,11 @@ public int getChildCount() { /** * Returns the child at the specified index in this node's "virtual" * child array + * * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (variable != null) { @@ -79,8 +80,8 @@ public ProgramElement getChildAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - public ProgramElementName getIdentifier(){ - return (ProgramElementName) variable.name(); + public ProgramElementName getIdentifier() { + return (ProgramElementName) variable.name(); } @@ -93,41 +94,44 @@ public ProgramVariable getProgramVariable() { return variable; } + @Nonnull public SourceElement getFirstElement() { return variable; } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - variable.prettyPrint(p); + variable.prettyPrint(p); } /** * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnVariableReference(this); + v.performActionOnVariableReference(this); } /** * We do not have a prefix, so fake it! * This way we implement ReferencePrefix + * * @author VK */ public ReferencePrefix getReferencePrefix() { - return null; + return null; } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } /** * Gets the KeY java type. * * @param javaServ the java services - * @param ec the execution context + * @param ec the execution context * @return the KeY java type */ public KeYJavaType getKeYJavaType(Services javaServ, @@ -136,10 +140,10 @@ public KeYJavaType getKeYJavaType(Services javaServ, } public KeYJavaType getKeYJavaType(Services javaServ) { - return getKeYJavaType(); + return getKeYJavaType(); } public KeYJavaType getKeYJavaType() { - return variable != null? variable.getKeYJavaType() : null; + return variable != null ? variable.getKeYJavaType() : null; } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchImp.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchImp.java index 22a5faab759..1b43bc734ec 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchImp.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchImp.java @@ -13,37 +13,29 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; import de.uka.ilkd.key.java.PositionInfo; +import org.key_project.util.ExtList; -/** - * Branch. - * @author AutoDoc - */ +import java.util.List; -public abstract class BranchImp - extends JavaNonTerminalProgramElement implements Branch { +public abstract class BranchImp extends JavaNonTerminalProgramElement implements Branch { + public BranchImp(PositionInfo pi, List comments) { + super(pi, comments); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * May contain: Comments - */ + * + * @param children the children of this AST element as KeY classes. + * May contain: Comments + */ public BranchImp(ExtList children) { - super(children); - } - - - public BranchImp() { - super(); + super(children); } - public BranchImp(ExtList children, PositionInfo pos) { super(children, pos); } - - } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchStatement.java index f3ddbe62c83..c394789e69d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/BranchStatement.java @@ -13,35 +13,39 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.NonTerminalProgramElement; +import de.uka.ilkd.key.java.PositionInfo; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.NonTerminalProgramElement; +import java.util.List; /** - * Branch statement. - * @author AL - * @author AutoDoc + * Branch statement. + * + * @author AL + * @author AutoDoc */ public abstract class BranchStatement extends JavaStatement implements NonTerminalProgramElement { - - public BranchStatement() { - + public BranchStatement(PositionInfo pi, List comments) { + super(pi, comments); } - /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments - */ + * May contain: Comments + */ public BranchStatement(ExtList children) { - super(children); + super(children); } /** - * Get the number of branches in this container. - * @return the number of branches. + * Get the number of branches in this container. + * + * @return the number of branches. */ public abstract int getBranchCount(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Break.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Break.java index 6a6a94f1c63..94cf41ecea6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Break.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Break.java @@ -13,52 +13,52 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Label; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Break. - * - */ +import java.util.List; public class Break extends LabelJumpStatement { - - /** - * Break. - */ + public Break(PositionInfo pi, List comments, Label name) { + super(pi, comments, name); + } public Break() { - super(); + super(null, null, null); } /** - * Break. - * @param label a name for the label. + * Break. + * + * @param label a name for the label. */ public Break(Label label) { - super(label); + super(null, null, label); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments, - * a ProgramElementName (as label of the label jump statement) - */ + * May contain: Comments, + * a ProgramElementName (as label of the label jump statement) + */ public Break(ExtList children) { - super(children); - // label=(ProgramElementName)children.get(ProgramElementName.class); + super(children); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnBreak(this); + v.performActionOnBreak(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Case.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Case.java index 08aad063675..96f8d512f06 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Case.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Case.java @@ -13,95 +13,90 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; + /** - * Case. - * + * Case. */ -public class Case extends BranchImp implements ExpressionContainer { +public final class Case extends BranchImp implements ExpressionContainer { + @Nonnull + private final Expression expression; - /** - * Expression. - */ - protected final Expression expression; + @Nonnull + private final ImmutableArray body; - /** - * Body. - */ - protected final ImmutableArray body; - /** - * Case. - */ - public Case() { - this.expression=null; - this.body=null; + public Case(PositionInfo pi, List comments, @Nonnull Expression expression, + @Nonnull ImmutableArray body) { + super(pi, comments); + this.expression = expression; + this.body = body; } /** - * Case. - * @param e an expression. + * Case. + * + * @param e an expression. */ public Case(Expression e) { - this.expression=e; - this.body=null; + this(null, null, e, new ImmutableArray<>()); } /** - * Case. - * @param e an expression. - * @param body a statement mutable list. + * Case. + * + * @param e an expression. + * @param body a statement mutable list. */ public Case(Expression e, Statement[] body) { - this.body=new ImmutableArray(body); - this.expression=e; + this(null, null, e, new ImmutableArray<>(body)); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments - * a Statement (as the statement following case) - * Must NOT contain: an Expression indicating the condition of the case - * as there are classes that are Expression and Statement, so they might - * get mixed up. Use the second parameter of this constructor for the - * expression. - * @param expr the expression of the case - */ + * May contain: Comments + * a Statement (as the statement following case) + * Must NOT contain: an Expression indicating the condition of the case + * as there are classes that are Expression and Statement, so they might + * get mixed up. Use the second parameter of this constructor for the + * expression. + * @param expr the expression of the case + */ public Case(ExtList children, Expression expr, PositionInfo pos) { - super(children, pos); - this.expression=expr; - this.body=new ImmutableArray(children.collect(Statement.class)); + super(children, pos); + this.expression = expr; + this.body = new ImmutableArray<>(children.collect(Statement.class)); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; if (expression != null) result++; - if (body != null) result += body.size(); + if (body != null) result += body.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -119,8 +114,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { @@ -143,8 +139,9 @@ public Expression getExpressionAt(int index) { } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { return (body != null) ? body.size() : 0; @@ -166,27 +163,30 @@ public Statement getStatementAt(int index) { } /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { return expression; } /** - * The body may be empty (null), to define a fall-through. - * Attaching an {@link EmptyStatement} would create a single ";". + * The body may be empty (null), to define a fall-through. + * Attaching an {@link EmptyStatement} would create a single ";". */ public ImmutableArray getBody() { return body; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnCase(this); + v.performActionOnCase(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Catch.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Catch.java index 4331f372303..5b00e2b2cfc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Catch.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Catch.java @@ -13,92 +13,81 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.ParameterContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.VariableScope; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.declaration.ParameterDeclaration; import de.uka.ilkd.key.java.visitor.Visitor; -/** - * Catch. - * - */ -public class Catch extends BranchImp implements ParameterContainer, - VariableScope { - - /** - * Parameter. - */ - - protected final ParameterDeclaration parameter; - - /** - * Body. - */ +import org.key_project.util.ExtList; - protected final StatementBlock body; +import javax.annotation.Nonnull; +import java.util.List; - /** - * Catch. - */ - public Catch() { - super(); - parameter=null; - body=null; +/** + * Catch. + */ +public class Catch extends BranchImp implements ParameterContainer, VariableScope { + @Nonnull + private final ParameterDeclaration parameter; + + @Nonnull + private final StatementBlock body; + + public Catch(PositionInfo pi, List comments, @Nonnull ParameterDeclaration parameter, + @Nonnull StatementBlock body) { + super(pi, comments); + this.parameter = parameter; + this.body = body; } /** - * Catch. - * @param e a parameter declaration. - * @param body a statement. + * Catch. + * + * @param e a parameter declaration. + * @param body a statement. */ - public Catch(ParameterDeclaration e, StatementBlock body) { - super(); - this.body=body; - parameter=e; + public Catch(@Nonnull ParameterDeclaration e, @Nonnull StatementBlock body) { + this(null, null, e, body); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments, - * a ParameterDeclaration (declaring the catched - * exceptions) - * a StatementBlock (as the action to do when catching) - */ + * May contain: Comments, + * a ParameterDeclaration (declaring the catched + * exceptions) + * a StatementBlock (as the action to do when catching) + */ public Catch(ExtList children) { - super(children); - parameter=children.get(ParameterDeclaration.class); - body=children.get(StatementBlock.class); + super(children); + parameter = children.get(ParameterDeclaration.class); + body = children.get(StatementBlock.class); } + @Nonnull public SourceElement getLastElement() { return (body != null) ? body.getLastElement() : this; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; if (parameter != null) result++; - if (body != null) result++; + if (body != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (parameter != null) { @@ -113,8 +102,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { return (body != null) ? 1 : 0; @@ -136,8 +126,9 @@ public Statement getStatementAt(int index) { } /** - * Get the number of parameters in this container. - * @return the number of parameters. + * Get the number of parameters in this container. + * + * @return the number of parameters. */ public int getParameterDeclarationCount() { return (parameter != null) ? 1 : 0; @@ -159,27 +150,31 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { } /** - * Get body. - * @return the statement. + * Get body. + * + * @return the statement. */ public Statement getBody() { return body; } /** - * Get parameter declaration. - * @return the parameter declaration. + * Get parameter declaration. + * + * @return the parameter declaration. */ public ParameterDeclaration getParameterDeclaration() { return parameter; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnCatch(this); + v.performActionOnCatch(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/CatchAllStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/CatchAllStatement.java index 298d7af0c64..c47d9b90199 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/CatchAllStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/CatchAllStatement.java @@ -13,105 +13,111 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.NonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.LocationVariable; +import org.key_project.util.ExtList; +import java.util.List; public class CatchAllStatement extends JavaNonTerminalProgramElement - implements Statement, - NonTerminalProgramElement, -// Desugarable, - StatementContainer { - private StatementBlock body; - private LocationVariable param; + implements Statement, NonTerminalProgramElement, StatementContainer { + + private final StatementBlock body; + private final LocationVariable param; + + public CatchAllStatement(PositionInfo pi, List comments, StatementBlock body, LocationVariable param) { + super(pi, comments); + this.body = body; + this.param = param; + } public CatchAllStatement(StatementBlock body, LocationVariable param) { - this.body = body; - this.param = param; + this(null, null, body, param); } - - + public CatchAllStatement(ExtList children) { - super(children); // for comments - this.body = children.get(StatementBlock.class); - this.param = children.get(LocationVariable.class); + super(children); // for comments + this.body = children.get(StatementBlock.class); + this.param = children.get(LocationVariable.class); } - - + + public Statement getBody() { - return body; + return body; } - + public LocationVariable getParam() { - return param; + return param; } - + /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { - int i=0; - if (body != null) i++; - if (param != null) i++; - return i; + int i = 0; + if (body != null) i++; + if (param != null) i++; + return i; } - + + @Override public Statement getStatementAt(int i) { return body; } - - + + + @Override public int getStatementCount() { return 1; } - - + + /** - * Returns the child at the specified index in this node's "virtual" - * child array. - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array. + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { - if (index == 0) { - return param; - } - if (index==1) { - return body; - } - throw new ArrayIndexOutOfBoundsException(); + if (index == 0) { + return param; + } + if (index == 1) { + return body; + } + throw new ArrayIndexOutOfBoundsException(); } - - - /** calls the corresponding method of a visitor in order to + + + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnCatchAllStatement(this); + v.performActionOnCatchAllStatement(this); } - + + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - p.printCatchAllStatement(this); + p.printCatchAllStatement(this); } - + // public Object desugar() { // IProgramVariable pv = getParameterDeclaration() diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Ccatch.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Ccatch.java index 45085c418ac..f7f12b7d0be 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Ccatch.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Ccatch.java @@ -13,109 +13,80 @@ package de.uka.ilkd.key.java.statement; -import java.util.Optional; - -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.CcatchNonstandardParameterDeclaration; -import de.uka.ilkd.key.java.ParameterContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.VariableScope; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.declaration.ParameterDeclaration; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * Ccatch. - * - */ -public class Ccatch extends BranchImp - implements ParameterContainer, VariableScope { +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; - /** - * Parameter. - */ - protected final Optional parameter; +public final class Ccatch extends BranchImp implements ParameterContainer, VariableScope { + @Nullable + private final ParameterDeclaration parameter; - private Optional nonStdParameter; + @Nullable + private final CcatchNonstandardParameterDeclaration nonStdParameter; - /** - * Body. - */ - protected final StatementBlock body; + private final StatementBlock body; - /** - * Ccatch. - */ - public Ccatch() { - super(); - parameter = Optional.empty(); - body = null; + public Ccatch(PositionInfo pi, List comments, @Nullable ParameterDeclaration parameter, + @Nullable CcatchNonstandardParameterDeclaration nonStdParameter, StatementBlock body) { + super(pi, comments); + this.parameter = parameter; + this.nonStdParameter = nonStdParameter; + this.body = body; } /** * Ccatch. * - * @param e - * a parameter declaration. - * @param body - * a statement. + * @param e a parameter declaration. + * @param body a statement. */ public Ccatch(ParameterDeclaration e, StatementBlock body) { - super(); - this.body = body; - parameter = Optional.of(e); - nonStdParameter = Optional.empty(); + this(null, null, e, null, body); } /** * Ccatch. * - * @param e - * a parameter declaration. - * @param body - * a statement. + * @param e a parameter declaration. + * @param body a statement. */ - public Ccatch(CcatchNonstandardParameterDeclaration e, - StatementBlock body) { - super(); - this.body = body; - parameter = Optional.empty(); - nonStdParameter = Optional.of(e); + public Ccatch(CcatchNonstandardParameterDeclaration e, StatementBlock body) { + this(null, null, null, e, body); + } /** * Constructor for the transformation of COMPOST ASTs to KeY. * - * @param children - * the children of this AST element as KeY classes. May contain: - * Comments, a ParameterDeclaration (declaring the catched - * exceptions) a StatementBlock (as the action to do when - * catching) + * @param children the children of this AST element as KeY classes. May contain: + * Comments, a ParameterDeclaration (declaring the catched + * exceptions) a StatementBlock (as the action to do when + * catching) */ public Ccatch(ExtList children) { super(children); - parameter = Optional - .ofNullable(children.get(ParameterDeclaration.class)); - nonStdParameter = Optional.ofNullable( - children.get(CcatchNonstandardParameterDeclaration.class)); + parameter = children.get(ParameterDeclaration.class); + nonStdParameter = children.get(CcatchNonstandardParameterDeclaration.class); body = children.get(StatementBlock.class); } + @Nonnull @Override public SourceElement getLastElement() { return (body != null) ? body.getLastElement() : this; } public boolean hasParameterDeclaration() { - return parameter.isPresent(); + return parameter != null; } public boolean hasNonStdParameterDeclaration() { - return nonStdParameter.isPresent(); + return nonStdParameter != null; } /** @@ -139,22 +110,20 @@ public int getChildCount() { * Returns the child at the specified index in this node's "virtual" child * array * - * @param index - * an index into this node's "virtual" child array + * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { if (hasParameterDeclaration()) { if (index == 0) - return parameter.get(); + return parameter; index--; } if (hasNonStdParameterDeclaration()) { if (index == 0) - return nonStdParameter.get(); + return nonStdParameter; index--; } if (body != null) { @@ -208,18 +177,14 @@ public int getParameterDeclarationCount() { * Return the parameter declaration at the specified index in this node's * "virtual" parameter declaration array. * - * @param index - * an index for a parameter declaration. - * + * @param index an index for a parameter declaration. * @return the parameter declaration with the given index. - * - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public ParameterDeclaration getParameterDeclarationAt(int index) { if (hasParameterDeclaration() && index == 0) { - return parameter.get(); + return parameter; } throw new ArrayIndexOutOfBoundsException(); } @@ -228,18 +193,14 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { * Return the non-standard parameter declaration at the specified index in * this node's "virtual" parameter declaration array. * - * @param index - * an index for a parameter declaration. - * + * @param index an index for a parameter declaration. * @return the parameter declaration with the given index. - * - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ public CcatchNonstandardParameterDeclaration getNonStdParameterDeclarationAt( int index) { if (hasNonStdParameterDeclaration() && index == 0) { - return nonStdParameter.get(); + return nonStdParameter; } throw new ArrayIndexOutOfBoundsException(); } @@ -259,7 +220,7 @@ public Statement getBody() { * @return the parameter declaration. */ public ParameterDeclaration getParameterDeclaration() { - return parameter.orElse(null); + return parameter; } /** @@ -268,15 +229,14 @@ public ParameterDeclaration getParameterDeclaration() { * @return the parameter declaration. */ public CcatchNonstandardParameterDeclaration getNonStdParameterDeclaration() { - return nonStdParameter.orElse(null); + return nonStdParameter; } /** * calls the corresponding method of a visitor in order to perform some * action/transformation on this element * - * @param v - * the Visitor + * @param v the Visitor */ @Override public void visit(Visitor v) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Continue.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Continue.java index b2607aea2cd..ce79e6d5b16 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Continue.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Continue.java @@ -13,28 +13,35 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Label; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import java.util.List; /** - * Continue. - * + * Continue. */ public class Continue extends LabelJumpStatement { + public Continue(PositionInfo pi, List comments, Label name) { + super(pi, comments, name); + } + /** - * Continue. + * Continue. */ public Continue() { - super(); + super(null, null, null); } /** - * Continue. - * @param label an identifier. + * Continue. + * + * @param label an identifier. */ public Continue(Label label) { super(label); @@ -42,20 +49,23 @@ public Continue(Label label) { /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments, - * a ProgramElementName (as label of the label jump statement) - */ + * May contain: Comments, + * a ProgramElementName (as label of the label jump statement) + */ public Continue(ExtList children) { - super(children); + super(children); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnContinue(this); + v.performActionOnContinue(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Default.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Default.java index 310be012f98..4b1cb6b61f2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Default.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Default.java @@ -13,54 +13,52 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; + /** - * Default. - * + * Default. */ -public class Default extends BranchImp { - - /** - * Body. - */ - protected final ImmutableArray body; +public final class Default extends BranchImp { + @Nonnull + private final ImmutableArray body; - /** - * Default. - */ - public Default() { - this.body=null; + public Default(PositionInfo pi, List comments, @Nonnull ImmutableArray body) { + super(pi, comments); + this.body = body; } /** - * Default. - * @param body a statement array. + * Default. + * + * @param body a statement array. */ public Default(Statement[] body) { - this.body=new ImmutableArray(body); + this(null, null, new ImmutableArray<>(body)); } - /** - * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * May contain: Comments, - * several of Statement (as the statements for Default) - */ + /** + * Constructor for the transformation of COMPOST ASTs to KeY. + * + * @param children the children of this AST element as KeY classes. + * May contain: Comments, + * several of Statement (as the statements for Default) + */ public Default(ExtList children) { - super(children); - this.body=new ImmutableArray(children.collect(Statement.class)); + super(children); + this.body = new ImmutableArray(children.collect(Statement.class)); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; @@ -69,12 +67,13 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -88,8 +87,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { return (body != null) ? body.size() : 0; @@ -111,19 +111,21 @@ public Statement getStatementAt(int index) { } /** - * The body may be empty (null), to define a fall-through. - * Attaching an {@link EmptyStatement} would create a single ";". + * The body may be empty (null), to define a fall-through. + * Attaching an {@link EmptyStatement} would create a single ";". */ public ImmutableArray getBody() { return body; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnDefault(this); + v.performActionOnDefault(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Do.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Do.java index 93f463cfee5..dbd7c97d13a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Do.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Do.java @@ -13,72 +13,72 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; /** - * Do. - * + * Do. */ public class Do extends LoopStatement { - - /** - * Do. - */ - public Do() { - super(); + public Do(PositionInfo pi, List comments, IGuard guard, Statement body) { + super(pi, comments, null, null, guard, body); } /** - * Do. - * @param guard an expression. + * Do. + * + * @param guard an expression. */ public Do(Expression guard) { super(guard); } /** - * Do. - * @param guard an expression. - * @param body a statement. + * Do. + * + * @param guard an expression. + * @param body a statement. */ public Do(Expression guard, Statement body, ExtList l, PositionInfo pos) { - super(guard, body, l, pos); + super(guard, body, l, pos); } /** - * Do. - * @param guard an expression. - * @param body a statement. + * Do. + * + * @param guard an expression. + * @param body a statement. */ public Do(Expression guard, Statement body, PositionInfo pos) { - super(guard, body, pos); + super(guard, body, pos); } + @Nonnull public SourceElement getLastElement() { return this; } /** - * Is checked before iteration. - * @return the boolean value. + * Is checked before iteration. + * + * @return the boolean value. */ public boolean isCheckedBeforeIteration() { return false; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnDo(this); + v.performActionOnDo(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Else.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Else.java index e28901d00a3..ca1a9038651 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Else.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Else.java @@ -13,81 +13,81 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; -/** - * Else. - */ +public final class Else extends BranchImp { + @Nonnull + private final Statement body; -public class Else extends BranchImp { - /** - * Body. - */ - protected Statement body; + public Else(PositionInfo pi, List comments, @Nonnull Statement body) { + super(pi, comments); + this.body = body; + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: a Body (as body of Else), Comments - */ + * May contain: a Body (as body of Else), Comments + */ public Else(ExtList children) { - super(children); - body=children.get(Statement.class); + super(children); + body = children.get(Statement.class); } - - /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param body Statement that is the body of the else part - */ - public Else(Statement body) { - this.body = body; + */ + public Else(@Nonnull Statement body) { + this(null, null, body); } + @Nonnull public SourceElement getLastElement() { return body.getLastElement(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { - return (body != null) ? 1 : 0; + return 1; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (body != null) { - if (index == 0) return body; - } + if (index == 0) return body; throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { - return (body != null) ? 1 : 0; + return 1; } /* @@ -99,26 +99,29 @@ public int getStatementCount() { of bounds. */ public Statement getStatementAt(int index) { - if (body != null && index == 0) { + if (index == 0) { return body; } throw new ArrayIndexOutOfBoundsException(); } /** - * The body may be empty (null), to define a fall-through. - * Attaching an {@link EmptyStatement} would create a single ";". + * The body may be empty (null), to define a fall-through. + * Attaching an {@link EmptyStatement} would create a single ";". */ + @Nonnull public Statement getBody() { return body; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnElse(this); + v.performActionOnElse(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EmptyStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EmptyStatement.java index 50ac5f5ce69..76d0232be4d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EmptyStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EmptyStatement.java @@ -13,49 +13,60 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.JavaProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.TerminalProgramElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; +import java.util.List; /** - * Empty statement. - * @author AutoDoc + * Empty Java statement. In Java written as a single semicolon ";". */ -public class EmptyStatement extends JavaProgramElement - implements Statement, TerminalProgramElement { +public final class EmptyStatement extends JavaProgramElement implements Statement, TerminalProgramElement { /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - */ + */ + @Deprecated public EmptyStatement(ExtList children) { - super(children); + super(children); } /** * Constructor for the transformation of COMPOST ASTs to KeY. * May contain: Comments - */ + */ public EmptyStatement() { - super(); + super(); + } + + public EmptyStatement(List comments) { + super(comments); } - /** calls the corresponding method of a visitor in order to + public EmptyStatement(PositionInfo pi, List comments) { + super(pi, comments); + } + + public EmptyStatement(PositionInfo pos) { + super(pos); + } + + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnEmptyStatement(this); + v.performActionOnEmptyStatement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printEmptyStatement(this); } - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EnhancedFor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EnhancedFor.java index 7e8c5ae644d..55032dfa244 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EnhancedFor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/EnhancedFor.java @@ -24,6 +24,8 @@ import de.uka.ilkd.key.java.visitor.CreatingASTVisitor; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * The new enhanced form of a for-loop. * @@ -78,6 +80,7 @@ public EnhancedFor(ExtList children) { * @see de.uka.ilkd.key.java.statement.For#getLastElement() * @see de.uka.ilkd.key.java.JavaSourceElement#getLastElement() */ + @Nonnull public SourceElement getLastElement() { return (body != null) ? body.getLastElement() : this; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Exec.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Exec.java index 4590f07e473..640d3fa7802 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Exec.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Exec.java @@ -13,49 +13,39 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramPrefix; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Exec. - * - * @author AutoDoc - */ -public class Exec extends BranchStatement - implements StatementContainer, ProgramPrefix { +import javax.annotation.Nonnull; +import java.util.List; - /** - * Body. - */ - private final StatementBlock body; - /** - * Branches. - */ +public class Exec extends BranchStatement implements StatementContainer, ProgramPrefix { + private final StatementBlock body; private final ImmutableArray branches; - private final MethodFrame innerMostMethodFrame; - private final int prefixLength; + public Exec(PositionInfo pi, List comments, StatementBlock body, ImmutableArray branches, + MethodFrame innerMostMethodFrame, int prefixLength) { + super(pi, comments); + this.body = body; + this.branches = branches; + this.innerMostMethodFrame = innerMostMethodFrame; + this.prefixLength = prefixLength; + } + /** * Exec. * - * @param body - * a statement block. + * @param body a statement block. */ public Exec(StatementBlock body) { + super(null, null); this.body = body; this.branches = null; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil @@ -67,12 +57,11 @@ public Exec(StatementBlock body) { /** * Exec. * - * @param body - * a statement block. - * @param branches - * a branch array. + * @param body a statement block. + * @param branches a branch array. */ public Exec(StatementBlock body, Branch[] branches) { + super(null, null); this.body = body; this.branches = new ImmutableArray(branches); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil @@ -85,12 +74,11 @@ public Exec(StatementBlock body, Branch[] branches) { /** * Exec. * - * @param body - * a statement block. - * @param branches - * a branch array. + * @param body a statement block. + * @param branches a branch array. */ public Exec(StatementBlock body, ImmutableArray branches) { + super(null, null); this.body = body; this.branches = branches; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil @@ -103,14 +91,13 @@ public Exec(StatementBlock body, ImmutableArray branches) { /** * Exec. * - * @param children - * a list with all children + * @param children a list with all children */ public Exec(ExtList children) { super(children); this.body = children.get(StatementBlock.class); this.branches = new ImmutableArray( - children.collect(Branch.class)); + children.collect(Branch.class)); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil .computeEssentials(this); prefixLength = info.getLength(); @@ -130,7 +117,7 @@ public ProgramPrefix getNextPrefixElement() { return (ProgramPrefix) body.getStatementAt(0); } else { throw new IndexOutOfBoundsException( - "No next prefix element " + this); + "No next prefix element " + this); } } @@ -156,11 +143,13 @@ public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); } + @Nonnull @Override public SourceElement getFirstElement() { return body.getFirstElement(); } + @Nonnull @Override public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); @@ -185,11 +174,9 @@ public int getChildCount() { * Returns the child at the specified index in this node's "virtual" child * array * - * @param index - * an index into this node's "virtual" child array + * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -228,13 +215,9 @@ public int getStatementCount() { * Return the statement at the specified index in this node's "virtual" * statement array. * - * @param index - * an index for a statement. - * + * @param index an index for a statement. * @return the statement with the given index. - * - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { @@ -258,11 +241,9 @@ public int getBranchCount() { * Return the branch at the specified index in this node's "virtual" branch * array. * - * @param index - * an index for a branch. + * @param index an index for a branch. * @return the branch with the given index. - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Branch getBranchAt(int index) { @@ -285,8 +266,7 @@ public ImmutableArray getBranchList() { * calls the corresponding method of a visitor in order to perform some * action/transformation on this element * - * @param v - * the Visitor + * @param v the Visitor */ @Override public void visit(Visitor v) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ExpressionJumpStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ExpressionJumpStatement.java index f48290dccab..34bd2683ac4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ExpressionJumpStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ExpressionJumpStatement.java @@ -13,66 +13,73 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.ProgramElement; +import javax.annotation.Nonnull; +import java.util.List; + /** - * Expression jump statement. - * @author AutoDoc + * Expression jump statement. + * + * @author AutoDoc */ public abstract class ExpressionJumpStatement extends JumpStatement implements ExpressionContainer { + @Nonnull + private final Expression expression; - /** - * Expression. - */ - - protected final Expression expression; + public ExpressionJumpStatement(PositionInfo pi, List comments, @Nonnull Expression expression) { + super(pi, comments); + this.expression = expression; + } /** * Expression jump statement. * May contain: an Expression (as expression of the - * ExpressionJumpStatement), - * Comments + * ExpressionJumpStatement), + * Comments */ public ExpressionJumpStatement(ExtList children) { - super(children); - expression=children.get(Expression.class); + super(children); + expression = children.get(Expression.class); } /** - * Expression jump statement. + * Expression jump statement. */ + @Deprecated public ExpressionJumpStatement() { - expression=null; + this(null, null, null); } /** - * Expression jump statement. - * @param expr an Expression used to jump + * Expression jump statement. + * + * @param expr an Expression used to jump */ public ExpressionJumpStatement(Expression expr) { - expression=expr; + this(null, null, expr); } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { return (expression != null) ? 1 : 0; } /** - Return the expression at the specified index in this node's - "virtual" expression array. - @param index an index for an expression. - @return the expression with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the expression at the specified index in this node's + * "virtual" expression array. + * + * @param index an index for an expression. + * @return the expression with the given index. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. + */ public Expression getExpressionAt(int index) { if (expression != null && index == 0) { return expression; @@ -81,16 +88,18 @@ public Expression getExpressionAt(int index) { } /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { return expression; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { return (expression != null) ? 1 : 0; @@ -99,10 +108,11 @@ public int getChildCount() { /** * Returns the child at the specified index in this node's "virtual" * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (expression != null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Finally.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Finally.java index 9b5ad40ca9d..2a536abb89e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Finally.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Finally.java @@ -13,56 +13,50 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; /** - * Finally. - * + * Finally. */ -public class Finally extends BranchImp { +public final class Finally extends BranchImp { + private final StatementBlock body; - /** - * Body. - */ - protected StatementBlock body; - - /** - * Finally. - */ - public Finally() { - body=null; + public Finally(PositionInfo pi, List comments, StatementBlock body) { + super(pi, comments); + this.body = body; } /** - * Finally. - * @param body a statement. + * Finally. + * + * @param body a statement. */ public Finally(StatementBlock body) { - this.body = body; + this(null, null, body); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: a Body (as body of the Finally), Comments - */ + * May contain: a Body (as body of the Finally), Comments + */ public Finally(ExtList children) { - super(children); - body=children.get(StatementBlock.class); + super(children); + body = children.get(StatementBlock.class); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; if (body != null) result++; @@ -70,12 +64,13 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (body != null) { @@ -85,9 +80,10 @@ public ProgramElement getChildAt(int index) { } - /** - * Get the number of statements in this container. - * @return the number of statements. + /** + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { return (body != null) ? 1 : 0; @@ -109,23 +105,27 @@ public Statement getStatementAt(int index) { } /** - * Get body. - * @return the statement. + * Get body. + * + * @return the statement. */ public Statement getBody() { return body; } + @Nonnull public SourceElement getLastElement() { return body; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnFinally(this); + v.performActionOnFinally(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/For.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/For.java index 6b365a496e4..b8d5d6efe41 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/For.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/For.java @@ -27,6 +27,8 @@ import de.uka.ilkd.key.java.declaration.VariableSpecification; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * For. * @@ -78,6 +80,7 @@ public For(ExtList children) { children); } + @Nonnull public SourceElement getLastElement() { return (body != null) ? body.getLastElement() : this; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ForUpdates.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ForUpdates.java index f38ee66208e..5ec3fafa994 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ForUpdates.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ForUpdates.java @@ -11,47 +11,47 @@ // Public License. See LICENSE.TXT for details. // -/** - * This class encapsulates updates of a for loop - */ - package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.util.List; -public class ForUpdates extends JavaNonTerminalProgramElement - implements ExpressionContainer, IForUpdates{ +/** + * This class encapsulates updates of a for loop + */ +public class ForUpdates extends JavaNonTerminalProgramElement implements ExpressionContainer, IForUpdates { + private final ImmutableArray updates; - ImmutableArray updates; + public ForUpdates(PositionInfo pi, List comments, ImmutableArray updates) { + super(pi, comments); + this.updates = updates; + } public ForUpdates(ImmutableArray exprarr) { - updates = exprarr; + this(null, null, exprarr); } public ForUpdates(ExtList ups, PositionInfo pos) { super(pos); - Expression[] exps = new Expression[ups.size()]; - for (int i = 0; i < exps.length; i++) { - exps[i] = (Expression)ups.get(i); - } - updates = new ImmutableArray(exps); + Expression[] exps = new Expression[ups.size()]; + for (int i = 0; i < exps.length; i++) { + exps[i] = (Expression) ups.get(i); + } + updates = new ImmutableArray<>(exps); } - + /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { - return updates.size(); + return updates.size(); } /* @@ -63,27 +63,27 @@ public int getExpressionCount() { of bounds. */ public Expression getExpressionAt(int index) { - return updates.get(index); + return updates.get(index); } public int size() { - return getExpressionCount(); + return getExpressionCount(); } public ImmutableArray getUpdates() { - return updates; + return updates; } - + public void visit(Visitor v) { - v.performActionOnForUpdates(this); + v.performActionOnForUpdates(this); } public int getChildCount() { - return getExpressionCount(); + return getExpressionCount(); } public ProgramElement getChildAt(int index) { - return getExpressionAt(index); + return getExpressionAt(index); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Guard.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Guard.java index beaf5b8f4d4..39423943eac 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Guard.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Guard.java @@ -11,50 +11,55 @@ // Public License. See LICENSE.TXT for details. // -/** - * This class encapsulates a guard for a loop - */ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; +import java.util.List; -public class Guard extends JavaNonTerminalProgramElement - implements IGuard { +/** + * This class encapsulates a guard for a loop + */ +public final class Guard extends JavaNonTerminalProgramElement implements IGuard { + @Nonnull + private final Expression expr; - Expression expr; + public Guard(PositionInfo pi, List comments, Expression expr) { + super(pi, comments); + this.expr = expr; + } public Guard(Expression expression) { - expr=expression; + this(null, null, expression); } public Guard(ExtList children) { - expr=children.get(Expression.class); + super(children); + expr = children.get(Expression.class); } public Expression getExpression() { - return expr; + return expr; } public void visit(Visitor v) { - v.performActionOnGuard(this); + v.performActionOnGuard(this); } public int getChildCount() { - return (expr!=null) ? 1 : 0; + return 1; } public ProgramElement getChildAt(int index) { - if (index==0) return expr; - return null; + if (index == 0) return expr; + return null; } - - public String toString(){ + + public String toString() { return expr.toString(); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/If.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/If.java index 57225c86246..4a86b20ce25 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/If.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/If.java @@ -13,44 +13,31 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; -/** - * If. - * @author AutoDoc - */ -public class If extends BranchStatement implements ExpressionContainer { - - /** - * Then branch. - */ - - protected Then thenBranch; - - /** - * Else branch. - */ - - protected Else elseBranch; +import javax.annotation.Nonnull; +import java.util.List; - /** - * Expression. - */ +public final class If extends BranchStatement implements ExpressionContainer { + private final Expression expression; + private final Then thenBranch; + private final Else elseBranch; - protected Expression expression; + public If(PositionInfo pi, List comments, Expression condition, Then thenBranch, Else elseBranch) { + super(pi, comments); + this.thenBranch = thenBranch; + this.elseBranch = elseBranch; + this.expression = condition; + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments, a Then, an Else, an Expression (as condition of If) - */ + * May contain: Comments, a Then, an Else, an Expression (as condition of If) + */ public If(ExtList children) { super(children); thenBranch = children.get(Then.class); @@ -66,14 +53,15 @@ private void checkValidity() { if (expression == null) { throw new NullPointerException("Guard of if-statement cannot be null."); } else if (thenBranch == null) { - throw new NullPointerException("Then-branch of if-statement cannot be null."); + throw new NullPointerException("Then-branch of if-statement cannot be null."); } } /** - * If. - * @param e an expression. - * @param thenBranch a then. + * If. + * + * @param e an expression. + * @param thenBranch a then. */ public If(Expression e, Then thenBranch) { @@ -81,30 +69,30 @@ public If(Expression e, Then thenBranch) { } /** - * If. - * @param e an expression. - * @param thenBranch a then. - * @param elseBranch an else. + * If. + * + * @param e an expression. + * @param thenBranch a then. + * @param elseBranch an else. */ public If(Expression e, Then thenBranch, Else elseBranch) { - this.expression = e; - this.thenBranch=thenBranch; - this.elseBranch=elseBranch; + this(null, null, e, thenBranch, elseBranch); checkValidity(); } /** - * * @return */ + @Nonnull public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { if (elseBranch != null) { @@ -114,14 +102,15 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ - public ProgramElement getChildAt(int index) { + public ProgramElement getChildAt(int index) { if (expression != null) { if (index == 0) return expression; index--; @@ -137,8 +126,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { return 1; @@ -160,33 +150,37 @@ public Expression getExpressionAt(int index) { } /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { return expression; } - + /** - * Get then. - * @return the then. + * Get then. + * + * @return the then. */ public Then getThen() { return thenBranch; } /** - * Get else. - * @return the else. + * Get else. + * + * @return the else. */ public Else getElse() { return elseBranch; } /** - * Get the number of branches in this container. - * @return the number of branches. + * Get the number of branches in this container. + * + * @return the number of branches. */ public int getBranchCount() { int result = 1; @@ -212,12 +206,14 @@ public Branch getBranchAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnIf(this); + v.performActionOnIf(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JavaStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JavaStatement.java index 61785560359..8897e9cc5b0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JavaStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JavaStatement.java @@ -13,39 +13,39 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.Statement; +import org.key_project.util.ExtList; + +import java.util.List; /** - * Default implementation for non-terminal Java statements. - * @author AutoDoc + * Default implementation for non-terminal Java statements. */ public abstract class JavaStatement - extends JavaNonTerminalProgramElement - implements Statement { + extends JavaNonTerminalProgramElement + implements Statement { - /** - * Java statement. - */ - public JavaStatement() { + public JavaStatement(PositionInfo pi, List comments) { + super(pi, comments); } /** - * Java statement. + * Java statement. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments + * May contain: Comments */ public JavaStatement(ExtList children) { - super(children); + super(children); } public JavaStatement(ExtList children, PositionInfo pos) { - super(children, pos); + super(children, pos); } public JavaStatement(PositionInfo pos) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JumpStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JumpStatement.java index 919b5ecc6d5..9ed706c68ae 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JumpStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JumpStatement.java @@ -13,28 +13,24 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.Comment; +import de.uka.ilkd.key.java.PositionInfo; import org.key_project.util.ExtList; -/** - * Jump statement. - * @author AutoDoc - */ -public abstract class JumpStatement extends JavaStatement { +import java.util.List; +public abstract class JumpStatement extends JavaStatement { /** - * Jump statement. + * Jump statement. + * * @param children the children of this AST element as KeY classes. - * May contain: Comments + * May contain: Comments */ public JumpStatement(ExtList children) { - super(children); + super(children); } - - /** - * Jump statement. - */ - public JumpStatement() { + public JumpStatement(PositionInfo pi, List comments) { + super(pi, comments); } - } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabelJumpStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabelJumpStatement.java index 2132378b950..fbfdaa9cb60 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabelJumpStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabelJumpStatement.java @@ -14,66 +14,69 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Label; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.reference.NameReference; import de.uka.ilkd.key.logic.ProgramElementName; +import org.key_project.util.ExtList; + +import javax.annotation.Nullable; +import java.util.List; + /** - * Label jump statement. - * + * Label jump statement. */ public abstract class LabelJumpStatement extends JumpStatement implements NameReference { /** - * Name. + * Name. */ + @Nullable + private final Label name; - protected final Label name; - - /** - * Label jump statement. - */ - - public LabelJumpStatement() { - name=null; + public LabelJumpStatement(PositionInfo pi, List comments, Label name) { + super(pi, comments); + this.name = name; } + /** - * Label jump statement. + * Label jump statement. + * * @param label the Label of this jump statement */ public LabelJumpStatement(Label label) { - super(); - name=label; - + this(null, null, label); } - - /** + + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. */ public LabelJumpStatement(ExtList children) { - super(children); - name=children.get(Label.class); + super(children); + name = children.get(Label.class); } - /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ public final String getName() { return (name == null) ? null : name.toString(); } /** - * Get Label. - * @return the Label label + * Get Label. + * + * @return the Label label */ public Label getLabel() { @@ -82,31 +85,34 @@ public Label getLabel() { /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public ProgramElementName getProgramElementName() { - if ((name instanceof ProgramElementName) || (name==null)) { - return (ProgramElementName) name; - } - return null; + if ((name instanceof ProgramElementName) || (name == null)) { + return (ProgramElementName) name; + } + return null; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { return (name != null) ? 1 : 0; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { if (name != null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabeledStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabeledStatement.java index 81fc511a925..f70a0614aec 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabeledStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LabeledStatement.java @@ -13,67 +13,54 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Label; -import de.uka.ilkd.key.java.NameAbstractionTable; -import de.uka.ilkd.key.java.NamedProgramElement; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramElementName; import de.uka.ilkd.key.logic.ProgramPrefix; -import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Labeled statement. + * Labeled statement. */ -public class LabeledStatement extends JavaStatement - implements StatementContainer, - NamedProgramElement, - ProgramPrefix { - - /** - * Name. - */ - - protected final Label name; - - /** - * Body. - */ - - protected final Statement body; - - +public final class LabeledStatement extends JavaStatement + implements StatementContainer, NamedProgramElement, ProgramPrefix { + private final Label name; + private final Statement body; private final PosInProgram firstActiveChildPos; - private final int prefixLength; private final MethodFrame innerMostMethodFrame; - + + public LabeledStatement(PositionInfo pi, List comments, Label name, Statement body, + PosInProgram firstActiveChildPos, int prefixLength, MethodFrame innerMostMethodFrame) { + super(pi, comments); + this.name = name; + this.body = body; + this.firstActiveChildPos = firstActiveChildPos; + this.prefixLength = prefixLength; + this.innerMostMethodFrame = innerMostMethodFrame; + } + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: a Label (as name of the label) - * a Statement (as body of the labeled statement) - * Comments + * May contain: a Label (as name of the label) + * a Statement (as body of the labeled statement) + * Comments */ public LabeledStatement(ExtList children, Label label, PositionInfo pos) { - super(children, pos); - name=label; + super(children, pos); + name = label; - body=children.get(Statement.class); - firstActiveChildPos = body instanceof StatementBlock ? - ((StatementBlock)body).isEmpty() ? PosInProgram.TOP : + body = children.get(Statement.class); + firstActiveChildPos = body instanceof StatementBlock ? + ((StatementBlock) body).isEmpty() ? PosInProgram.TOP : PosInProgram.ONE_ZERO : PosInProgram.ONE; // otherwise it will crash later @@ -86,34 +73,36 @@ public LabeledStatement(ExtList children, Label label, PositionInfo pos) { } /** - * Labeled statement. - * @param name an identifier. + * Labeled statement. + * + * @param name an identifier. */ - public LabeledStatement(Label name) { - this.name=name; - body=new EmptyStatement(); - firstActiveChildPos = body instanceof StatementBlock ? - (((StatementBlock)body).isEmpty() ? PosInProgram.TOP : - PosInProgram.ONE_ZERO) : PosInProgram.ONE; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); - prefixLength = info.getLength(); - innerMostMethodFrame = info.getInnerMostMethodFrame(); + super((PositionInfo) null, null); + this.name = name; + body = new EmptyStatement(); + firstActiveChildPos = body instanceof StatementBlock ? + (((StatementBlock) body).isEmpty() ? PosInProgram.TOP : + PosInProgram.ONE_ZERO) : PosInProgram.ONE; + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + prefixLength = info.getLength(); + innerMostMethodFrame = info.getInnerMostMethodFrame(); } /** - * Labeled statement. - * @param id a Label. - * @param statement a statement. + * Labeled statement. + * + * @param id a Label. + * @param statement a statement. */ public LabeledStatement(Label id, Statement statement, PositionInfo pos) { super(pos); - this.name=id; - body=statement; - firstActiveChildPos = body instanceof StatementBlock ? - (((StatementBlock)body).isEmpty() ? PosInProgram.TOP : - PosInProgram.ONE_ZERO) : PosInProgram.ONE; + this.name = id; + body = statement; + firstActiveChildPos = body instanceof StatementBlock ? + (((StatementBlock) body).isEmpty() ? PosInProgram.TOP : + PosInProgram.ONE_ZERO) : PosInProgram.ONE; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -124,7 +113,7 @@ public boolean hasNextPrefixElement() { if (body instanceof ProgramPrefix) { if (body instanceof StatementBlock) { return !((StatementBlock) body).isEmpty() && - ((StatementBlock)body).getStatementAt(0) instanceof ProgramPrefix; + ((StatementBlock) body).getStatementAt(0) instanceof ProgramPrefix; } return true; } @@ -134,74 +123,78 @@ public boolean hasNextPrefixElement() { @Override public ProgramPrefix getNextPrefixElement() { if (hasNextPrefixElement()) { - return (ProgramPrefix) + return (ProgramPrefix) (body instanceof StatementBlock ? ((StatementBlock) body).getStatementAt(0) : body); } else { throw new IndexOutOfBoundsException("No next prefix element " + this); } } - + @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : - this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : + this; } - + @Override public ImmutableArray getPrefixElements() { if (body instanceof StatementBlock) { return StatementBlock.computePrefixElements - (((StatementBlock)body).getBody(), this); + (((StatementBlock) body).getBody(), this); } else if (body instanceof ProgramPrefix) { return StatementBlock. - computePrefixElements(new ImmutableArray(body), - this); - } - return new ImmutableArray(this); + computePrefixElements(new ImmutableArray<>(body), + this); + } + return new ImmutableArray<>(this); } + @Override + @Nonnull public SourceElement getFirstElement() { - if (body instanceof StatementBlock) { - return body.getFirstElement(); - } - else { - return body; - } + if (body instanceof StatementBlock) { + return body.getFirstElement(); + } else { + return body; + } } @Override public SourceElement getFirstElementIncludingBlocks() { - if (body instanceof StatementBlock) { - return body.getFirstElementIncludingBlocks(); - } - else { - return body; - } + if (body instanceof StatementBlock) { + return body.getFirstElementIncludingBlocks(); + } else { + return body; + } } + @Override + @Nonnull public SourceElement getLastElement() { - if (body instanceof StatementBlock) { - return body.getLastElement(); - } - else { - return body; - } + if (body instanceof StatementBlock) { + return body.getLastElement(); + } else { + return body; + } } /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ - public final String getName() { + @Override + public String getName() { return (name == null) ? null : name.toString(); } /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public Label getLabel() { @@ -210,30 +203,35 @@ public Label getLabel() { /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ + @Override public ProgramElementName getProgramElementName() { - if ((name instanceof ProgramElementName) || (name==null)) { - return (ProgramElementName) name; - } - LOGGER.debug("labeledstatement: SCHEMAVARIABLE IN LABELEDSTATEMENT"); - return null; + if ((name instanceof ProgramElementName) || (name == null)) { + return (ProgramElementName) name; + } + LOGGER.debug("labeledstatement: SCHEMAVARIABLE IN LABELEDSTATEMENT"); + return null; } /** - * Get body. - * @return the statement. + * Get body. + * + * @return the statement. */ public Statement getBody() { return body; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ + @Override public int getChildCount() { int result = 0; if (name != null) result++; @@ -242,14 +240,16 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ + @Override public ProgramElement getChildAt(int index) { if (name != null) { if (index == 0) return name; @@ -261,25 +261,29 @@ public ProgramElement getChildAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } - + /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ + @Override public int getStatementCount() { return (body != null) ? 1 : 0; } /** - * Return the statement at the specified index in this node's - * "virtual" statement array. - * @param index an index for a statement. - * @return the statement with the given index. - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds. + * Return the statement at the specified index in this node's + * "virtual" statement array. + * + * @param index an index for a statement. + * @return the statement with the given index. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. */ + @Override public Statement getStatementAt(int index) { if (body != null && index == 0) { return body; @@ -287,34 +291,41 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ + @Override public void visit(Visitor v) { - v.performActionOnLabeledStatement(this); + v.performActionOnLabeledStatement(this); } + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printLabeledStatement(this); } - /** testing if programelements are equal modulo renaming abstract + /** + * testing if programelements are equal modulo renaming abstract * from names. Therefore declaration of label names have to be * mapped to the same abstract name. This is done here. */ - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { - if (se == null || this.getClass() != se.getClass()) { - return false; - } - - final LabeledStatement lSt = (LabeledStatement)se; - - nat.add(name, lSt.name); - return super.equalsModRenaming(lSt, nat); + @Override + public boolean equalsModRenaming(SourceElement se, + NameAbstractionTable nat) { + if (se == null || this.getClass() != se.getClass()) { + return false; + } + + final LabeledStatement lSt = (LabeledStatement) se; + + nat.add(name, lSt.name); + return super.equalsModRenaming(lSt, nat); } - + + @Override public PosInProgram getFirstActiveChildPos() { return firstActiveChildPos; } @@ -328,5 +339,5 @@ public int getPrefixLength() { public MethodFrame getInnerMostMethodFrame() { return innerMostMethodFrame; } - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopInit.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopInit.java index fc5cd049641..7b64990521d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopInit.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopInit.java @@ -11,52 +11,51 @@ // Public License. See LICENSE.TXT for details. // -/** - * This class encapsulates initializers of a for loop - */ - package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.LoopInitializer; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementContainer; -import de.uka.ilkd.key.java.visitor.Visitor; +import java.util.List; -public class LoopInit extends JavaNonTerminalProgramElement - implements StatementContainer, ILoopInit{ +/** + * This class encapsulates initializers of a for loop + */ +public final class LoopInit extends JavaNonTerminalProgramElement implements StatementContainer, ILoopInit { + private final ImmutableArray inits; - ImmutableArray inits; + public LoopInit(PositionInfo pi, List comments, ImmutableArray inits) { + super(pi, comments); + this.inits = inits; + } public LoopInit(ImmutableArray exprarr) { - inits = exprarr; + this(null, null, exprarr); } public LoopInit(LoopInitializer[] exprarr) { - inits = new ImmutableArray(exprarr); + this(new ImmutableArray<>(exprarr)); } public LoopInit(ExtList ups, PositionInfo pos) { super(pos); - final LoopInitializer[] exps = new LoopInitializer[ups.size()]; - for (int i=0; i(exps); + final LoopInitializer[] exps = new LoopInitializer[ups.size()]; + for (int i = 0; i < exps.length; i++) { + exps[i] = (LoopInitializer) ups.get(i); + } + inits = new ImmutableArray<>(exps); } - + /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { - return inits.size(); + return inits.size(); } /* @@ -68,27 +67,27 @@ public int getStatementCount() { of bounds. */ public Statement getStatementAt(int index) { - return inits.get(index); + return inits.get(index); } public int size() { - return getStatementCount(); + return getStatementCount(); } public ImmutableArray getInits() { - return inits; + return inits; } - + public void visit(Visitor v) { - v.performActionOnLoopInit(this); + v.performActionOnLoopInit(this); } public int getChildCount() { - return getStatementCount(); + return getStatementCount(); } public ProgramElement getChildAt(int index) { - return getStatementAt(index); + return getStatementAt(index); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopScopeBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopScopeBlock.java index 33cfbd106e9..ec3b0c89448 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopScopeBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopScopeBlock.java @@ -13,43 +13,45 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramPrefix; import de.uka.ilkd.key.logic.op.IProgramVariable; import de.uka.ilkd.key.logic.op.ProgramVariable; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.List; /** * Loop scope block. TODO * * @author Dominic Scheurer */ -public class LoopScopeBlock extends JavaStatement +public final class LoopScopeBlock extends JavaStatement implements StatementContainer, ExpressionContainer, ProgramPrefix { - protected final IProgramVariable indexPV; - protected final StatementBlock body; + @Nullable + private final IProgramVariable indexPV; + @Nonnull + private final StatementBlock body; private final MethodFrame innerMostMethodFrame; private final int prefixLength; - /** - * TODO - * - * @param body - */ + public LoopScopeBlock(PositionInfo pi, List comments, IProgramVariable indexPV, + StatementBlock body, MethodFrame innerMostMethodFrame, int prefixLength) { + super(pi, comments); + this.indexPV = indexPV; + this.body = body; + this.innerMostMethodFrame = innerMostMethodFrame; + this.prefixLength = prefixLength; + } + public LoopScopeBlock(StatementBlock body) { + super((PositionInfo) null, null); this.body = body; this.indexPV = null; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil @@ -60,15 +62,15 @@ public LoopScopeBlock(StatementBlock body) { /** * TODO - * + * * @param e * @param body */ public LoopScopeBlock(IProgramVariable iProgramVariable, StatementBlock body) { + super((PositionInfo) null, null); this.indexPV = iProgramVariable; this.body = body; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -76,9 +78,8 @@ public LoopScopeBlock(IProgramVariable iProgramVariable, StatementBlock body) { /** * Synchronized block. - * - * @param children - * a list with all children + * + * @param children a list with all children */ public LoopScopeBlock(ExtList children) { super(children); @@ -136,7 +137,7 @@ public PosInProgram getFirstActiveChildPos() { /** * Get the number of expressions in this container. - * + * * @return the number of expressions. */ @Override @@ -147,12 +148,10 @@ public int getExpressionCount() { /** * Return the expression at the specified index in this node's "virtual" * expression array. - * - * @param index - * an index for an expression. + * + * @param index an index for an expression. * @return the expression with the given index. - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Expression getExpressionAt(int index) { @@ -164,7 +163,7 @@ public Expression getExpressionAt(int index) { /** * Get expression. - * + * * @return the expression. */ public IProgramVariable getIndexPV() { @@ -173,7 +172,7 @@ public IProgramVariable getIndexPV() { /** * Returns the number of children of this node. - * + * * @return an int giving the number of children of this node */ @Override @@ -181,20 +180,17 @@ public int getChildCount() { int result = 0; if (indexPV != null) result++; - if (body != null) - result++; + result++; return result; } /** * Returns the child at the specified index in this node's "virtual" child * array - * - * @param index - * an index into this node's "virtual" child array + * + * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -203,16 +199,14 @@ public ProgramElement getChildAt(int index) { return indexPV; index--; } - if (body != null) { - if (index == 0) - return body; - } + if (index == 0) + return body; throw new ArrayIndexOutOfBoundsException(); } /** * Get body. - * + * * @return the statement block. */ public StatementBlock getBody() { @@ -221,34 +215,31 @@ public StatementBlock getBody() { /** * Get the number of statements in this container. - * + * * @return the number of statements. */ @Override public int getStatementCount() { - return (body != null && !body.isEmpty()) ? 1 : 0; + return !body.isEmpty() ? 1 : 0; } /** * Return the statement at the specified index in this node's "virtual" * statement array. - * - * @param index - * an index for a statement. - * + * + * @param index an index for a statement. * @return the statement with the given index. - * - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { - if (body != null && index == 0) { + if (index == 0) { return body; } throw new ArrayIndexOutOfBoundsException(); } + @Nonnull @Override public SourceElement getFirstElement() { return body.getFirstElement(); @@ -257,9 +248,8 @@ public SourceElement getFirstElement() { /** * Calls the corresponding method of a visitor in order to perform some * action/transformation on this element - * - * @param v - * the Visitor + * + * @param v the Visitor */ @Override public void visit(Visitor v) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopStatement.java index 7632bda5e64..633b19fe7a2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/LoopStatement.java @@ -13,240 +13,234 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.LoopInitializer; -import de.uka.ilkd.key.java.Position; -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementContainer; +import java.util.List; +import java.util.Objects; /** - * Loop statement. - * + * Loop statement. */ -public abstract class LoopStatement extends JavaStatement - implements StatementContainer, ExpressionContainer { +public abstract class LoopStatement extends JavaStatement + implements StatementContainer, ExpressionContainer { /** - * Inits. + * Inits. */ protected final ILoopInit inits; /** - * Updates. + * Updates. */ protected final IForUpdates updates; /** - * Guard. + * Guard. */ protected final IGuard guard; - + /** - * Body. + * Body. */ protected final Statement body; + public LoopStatement(PositionInfo pi, List comments, ILoopInit inits, IForUpdates updates, + IGuard guard, Statement body) { + super(pi, comments); + this.inits = inits; + this.updates = updates; + this.guard = guard; + this.body = body; + } + /** - * Loop statement. + * Loop statement. */ + @Deprecated public LoopStatement() { - this.body=null; - this.updates=null; - this.inits=null; - this.guard=null; + this((PositionInfo) null, null, null, null, null, null); } /** - * Loop statement. - * @param body a statement. + * Loop statement. + * + * @param body a statement. */ public LoopStatement(Statement body) { - this.body = body; - this.updates = null; - this.inits = null; - this.guard = null; + this(null, body); } - /** - * Loop statement. - * @param guard the guard expression. + /** + * Loop statement. + * + * @param guard the guard expression. */ public LoopStatement(Expression guard) { - this.body = null; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + this(null, null, null, null, new Guard(guard), null); } /** - * Loop statement. - * @param body a statement. + * Loop statement. + * + * @param body a statement. */ public LoopStatement(Expression guard, Statement body, ExtList comments) { - super(comments); - this.body = body; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + super(comments); + this.body = body; + this.updates = null; + this.inits = null; + this.guard = new Guard(guard); } public LoopStatement(Expression guard, Statement body, ExtList comments, PositionInfo pos) { - super(add(comments,pos)); - this.body = body; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + super(add(comments, pos)); + this.body = body; + this.updates = null; + this.inits = null; + this.guard = new Guard(guard); } /** - * Loop statement. - * @param body a statement. + * Loop statement. + * + * @param body a statement. */ public LoopStatement(Expression guard, Statement body) { - this.body = body; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + this(null, null, null, null, new Guard(guard), body); } public LoopStatement(Expression guard, Statement body, PositionInfo pos) { - super(pos); - this.body = body; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + super(pos); + this.body = body; + this.updates = null; + this.inits = null; + this.guard = new Guard(guard); } - /** - * Loop statement. This constructor is used for the transformation - * of Recoder to KeY. - * @param inits the initializers of the loop - * @param guard the guard of the loop - * @param updates the updates of the loop - * @param body the body of the loop - */ - public LoopStatement(LoopInitializer[] inits, Expression guard, - Expression[] updates, Statement body) { + /** + * Loop statement. This constructor is used for the transformation + * of Recoder to KeY. + * + * @param inits the initializers of the loop + * @param guard the guard of the loop + * @param updates the updates of the loop + * @param body the body of the loop + */ + public LoopStatement(LoopInitializer[] inits, Expression guard, + Expression[] updates, Statement body) { + super((PositionInfo) null, null); this.body = body; - if (updates!=null) { - this.updates = new ForUpdates - (new ImmutableArray(updates)); - } else { - this.updates = new ForUpdates(new ImmutableArray(new Expression[0])); - } - this.inits = new LoopInit(inits); - this.guard=new Guard(guard); + this.updates = new ForUpdates + (new ImmutableArray<>(Objects.requireNonNullElseGet(updates, () -> new Expression[0]))); + this.inits = new LoopInit(inits); + this.guard = new Guard(guard); } - /** - * Loop statement. This constructor is used for the transformation - * of Recoder to KeY. - * @param inits the initializers of the loop - * @param guard the guard of the loop - * @param updates the updates of the loop - * @param body the body of the loop - * @param comments the comments attached to this statement. - */ - public LoopStatement(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body, ExtList comments){ - super(comments); - this.body = body; - this.updates = updates; - this.inits = inits; - this.guard = guard; + /** + * Loop statement. This constructor is used for the transformation + * of Recoder to KeY. + * + * @param inits the initializers of the loop + * @param guard the guard of the loop + * @param updates the updates of the loop + * @param body the body of the loop + * @param comments the comments attached to this statement. + */ + public LoopStatement(ILoopInit inits, IGuard guard, IForUpdates updates, Statement body, ExtList comments) { + super(comments); + this.body = body; + this.updates = updates; + this.inits = inits; + this.guard = guard; + } + + + public LoopStatement(ILoopInit inits, IGuard guard, IForUpdates updates, Statement body, ExtList comments, + PositionInfo pos) { + super(add(comments, pos)); + this.body = body; + this.updates = updates; + this.inits = inits; + this.guard = guard; } - public LoopStatement(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body, ExtList comments, - PositionInfo pos){ - super(add(comments,pos)); - this.body = body; - this.updates = updates; - this.inits = inits; - this.guard = guard; + /** + * Loop statement. This constructor is used for the transformation + * of Recoder to KeY. + * + * @param inits the initializers of the loop + * @param guard the guard of the loop + * @param updates the updates of the loop + * @param body the body of the loop + * @param pos the position of the loop + */ + public LoopStatement(ILoopInit inits, IGuard guard, + IForUpdates updates, Statement body, + PositionInfo pos) { + super(pos); + this.body = body; + this.updates = updates; + this.inits = inits; + this.guard = guard; } /** * Loop statement. This constructor is used for the transformation * of Recoder to KeY. - * @param inits the initializers of the loop - * @param guard the guard of the loop + * + * @param inits the initializers of the loop + * @param guard the guard of the loop * @param updates the updates of the loop - * @param body the body of the loop - * @param pos the position of the loop + * @param body the body of the loop */ - public LoopStatement(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body, - PositionInfo pos) { - super(pos); - this.body = body; - this.updates = updates; - this.inits = inits; - this.guard = guard; - } - - - /** - * Loop statement. This constructor is used for the transformation - * of Recoder to KeY. - * @param inits the initializers of the loop - * @param guard the guard of the loop - * @param updates the updates of the loop - * @param body the body of the loop - */ public LoopStatement(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body) { - this.body = body; - this.updates = updates; - this.inits = inits; - this.guard = guard; + IForUpdates updates, Statement body) { + this(null, null, inits, updates, guard, body); } - static private ExtList add(ExtList e, Object o){ - e.add(o); - return e; + private static ExtList add(ExtList e, Object o) { + e.add(o); + return e; } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; - if (inits != null) result++; - if (guard != null) result++; + if (inits != null) result++; + if (guard != null) result++; if (updates != null) result++; - if (body != null) result++; + if (body != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (inits != null) { - if (index==0) { + if (inits != null) { + if (index == 0) { return inits; } index--; @@ -258,7 +252,7 @@ public ProgramElement getChildAt(int index) { } } if (updates != null) { - if (index==0) { + if (index == 0) { return updates; } index--; @@ -277,14 +271,15 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { int result = 0; if (guard != null) result += 1; if (inits != null) { - result +=1; + result += 1; } if (updates != null) { result += updates.size(); @@ -303,7 +298,7 @@ public int getExpressionCount() { public Expression getExpressionAt(int index) { if (guard != null) { if (index == 0) { - return (Expression)guard.getChildAt(0); + return (Expression) guard.getChildAt(0); } index -= 1; } @@ -313,7 +308,7 @@ public Expression getExpressionAt(int index) { final LoopInitializer ii = inits.getInits().get(i); if (ii instanceof Expression) { if (index == 0) { - return (Expression)ii; + return (Expression) ii; } index -= 1; } @@ -326,32 +321,36 @@ public Expression getExpressionAt(int index) { } /** - * Get guard. - * @return the expression. + * Get guard. + * + * @return the expression. */ public IGuard getGuard() { return guard; } /** - * Get guard. - * @return the expression. + * Get guard. + * + * @return the expression. */ public Expression getGuardExpression() { - return (Expression)guard.getChildAt(0); + return (Expression) guard.getChildAt(0); } /** - * Get body. - * @return the statement. + * Get body. + * + * @return the statement. */ public Statement getBody() { return body; } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { return (body != null) ? 1 : 0; @@ -373,47 +372,52 @@ public Statement getStatementAt(int index) { } /** - * Get initializers. - * @return the loop initializer array wrapper . + * Get initializers. + * + * @return the loop initializer array wrapper . */ public ImmutableArray getInitializers() { - if (inits != null) { - return inits.getInits(); - } - return null; + if (inits != null) { + return inits.getInits(); + } + return null; } - + /** - * Get updates. - * @return the expression mutable list. + * Get updates. + * + * @return the expression mutable list. */ public ImmutableArray getUpdates() { if (updates != null) { - return updates.getUpdates(); - } - return null; + return updates.getUpdates(); + } + return null; } /** - * Get updates as IForUpdates - * @return the expression mutable list. + * Get updates as IForUpdates + * + * @return the expression mutable list. */ public IForUpdates getIForUpdates() { return updates; } - + /** * get the loop initializer as ILoopInit + * * @return the loop initializer */ public ILoopInit getILoopInit() { - return inits; + return inits; } /** - * Is checked before iteration. - * @return the boolean value. + * Is checked before iteration. + * + * @return the boolean value. */ public abstract boolean isCheckedBeforeIteration(); @@ -423,11 +427,11 @@ public boolean equals(Object o) { return false; } - LoopStatement cmp = (LoopStatement)o; + LoopStatement cmp = (LoopStatement) o; return super.equals(cmp) && (this.getStartPosition().equals(Position.UNDEFINED) || - cmp.getStartPosition().equals(Position.UNDEFINED) || - this.getStartPosition().getLine() == cmp.getStartPosition().getLine()); + cmp.getStartPosition().equals(Position.UNDEFINED) || + this.getStartPosition().getLine() == cmp.getStartPosition().getLine()); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MergePointStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MergePointStatement.java index aeb8c8a7b0c..8e2a167db25 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MergePointStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MergePointStatement.java @@ -13,16 +13,14 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - -import de.uka.ilkd.key.java.Comment; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.IProgramVariable; import de.uka.ilkd.key.logic.op.LocationVariable; +import org.key_project.util.ExtList; + +import java.util.List; +import java.util.Objects; /** * A statement indicating a merge point. @@ -34,33 +32,38 @@ public class MergePointStatement extends JavaStatement // Those are used for JML to JavaDL conversions protected final IProgramVariable identifier; - protected final Comment[] comments; + + //TODO weigl revise extra comments + //protected final Comment[] comments; + + public MergePointStatement(PositionInfo pi, List comments, IProgramVariable identifier) { + super(pi, comments); + this.identifier = identifier; + } public MergePointStatement(IProgramVariable indexPV) { - this.identifier = indexPV; - this.comments = null; + this(null, null, indexPV); } public MergePointStatement(LocationVariable identifier, Comment[] comments) { - this.identifier = identifier; - this.comments = comments; + this(null, null, identifier); } public MergePointStatement(ExtList children) { super(children); - identifier = children.get(IProgramVariable.class); - assert identifier instanceof IProgramVariable; - comments = children.get(Comment[].class); + identifier = Objects.requireNonNull(children.get(IProgramVariable.class)); + //comments = children.get(Comment[].class); } - @Override +/* @Override public Comment[] getComments() { return comments; } +*/ /** * Get the number of expressions in this container. - * + * * @return the number of expressions. */ public int getExpressionCount() { @@ -70,14 +73,10 @@ public int getExpressionCount() { /** * Return the expression at the specified index in this node's "virtual" * expression array. - * - * @param index - * an index for an expression. - * + * + * @param index an index for an expression. * @return the expression with the given index. - * - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @throws ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { if (identifier != null && index == 0) { @@ -88,7 +87,7 @@ public Expression getExpressionAt(int index) { /** * Get expression. - * + * * @return the expression. */ public Expression getExpression() { @@ -97,7 +96,7 @@ public Expression getExpression() { /** * Returns the number of children of this node. - * + * * @return an int giving the number of children of this node */ public int getChildCount() { @@ -110,12 +109,10 @@ public int getChildCount() { /** * Returns the child at the specified index in this node's "virtual" child * array - * - * @param index - * an index into this node's "virtual" child array + * + * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (identifier != null) { @@ -129,9 +126,8 @@ public ProgramElement getChildAt(int index) { /** * calls the corresponding method of a visitor in order to perform some * action/transformation on this element - * - * @param v - * the Visitor + * + * @param v the Visitor */ public void visit(Visitor v) { v.performActionOnMergePointStatement(this); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodBodyStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodBodyStatement.java index 4cabfa02835..37d1ba0cdff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodBodyStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodBodyStatement.java @@ -13,234 +13,211 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.NonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.Statement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.reference.ExecutionContext; -import de.uka.ilkd.key.java.reference.MethodReference; -import de.uka.ilkd.key.java.reference.ReferencePrefix; -import de.uka.ilkd.key.java.reference.TypeRef; -import de.uka.ilkd.key.java.reference.TypeReference; +import de.uka.ilkd.key.java.reference.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.IProgramMethod; import de.uka.ilkd.key.logic.op.IProgramVariable; import de.uka.ilkd.key.logic.op.LocationVariable; import de.uka.ilkd.key.logic.op.SchemaVariable; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * A shortcut-statement for a method body, i.e. no dynamic dispatching - * any longer.

- * Please take care: - * only the method name plus the class in which class the method - * is implemented is part of the syntax representation of such a - * statement, but not the methods complete syntax. If there are - * two methods with an equal name, but different signature (i.e. - * parameter types), the pure syntax is ambigious. In fact the concrete body - * this method body statement represents depends on the static type of - * its arguments.

- * Therefore: Transformation of a method body statement MUST keep - * the static type of the arguments unchanged. - *

- * - * + * A shortcut-statement for a method body, i.e. no dynamic dispatching + * any longer.

+ * Please take care: + * only the method name plus the class in which class the method + * is implemented is part of the syntax representation of such a + * statement, but not the methods complete syntax. If there are + * two methods with an equal name, but different signature (i.e. + * parameter types), the pure syntax is ambigious. In fact the concrete body + * this method body statement represents depends on the static type of + * its arguments.

+ * Therefore: Transformation of a method body statement MUST keep + * the static type of the arguments unchanged. + *

*/ public class MethodBodyStatement extends JavaNonTerminalProgramElement - implements Statement, NonTerminalProgramElement { + implements Statement, NonTerminalProgramElement { + - - /** + /** * the variable the result of the method execution is assigned to - * if the method is declared void or the result not assigned to a + * if the method is declared void or the result not assigned to a * variable or field, this value is null. */ private final IProgramVariable resultVar; - + /** * This type reference determines the class where the represented method * has to be implemented. */ private final TypeReference bodySource; - /** + /** * the reference describing the method signature */ + @Nonnull private final MethodReference methodReference; - - /** cache resolved method */ + + /** + * cache resolved method + */ private IProgramMethod method; - /** indicates whether this stands for the specification of - * a method rather than the concrete body*/ - private boolean useSpecification; - + public MethodBodyStatement(PositionInfo pi, List comments, IProgramVariable resultVar, + TypeReference bodySource, MethodReference methodReference, IProgramMethod method) { + super(pi, comments); + this.resultVar = resultVar; + this.bodySource = bodySource; + this.methodReference = methodReference; + this.method = method; + } + /** - * Construct a method body shortcut - * @param bodySource exact class where the body is declared - * @param resultVar the IProgramVariable to which the method's return value is assigned - * @param methodReference the MethodReference encapsulating the method's signature + * Construct a method body shortcut + * + * @param bodySource exact class where the body is declared + * @param resultVar the IProgramVariable to which the method's return value is assigned + * @param methodReference the MethodReference encapsulating the method's signature */ - public MethodBodyStatement(TypeReference bodySource, - IProgramVariable resultVar, - MethodReference methodReference) { - this.bodySource = bodySource; - this.resultVar = resultVar; - this.methodReference = methodReference; - - assert methodReference != null : "Missing methodreference"; - assert methodReference.getReferencePrefix() != null : - "Method reference of a method body statement needs an " + - "explicit reference prefix."; - checkOnlyProgramVarsAsArguments(methodReference.getArguments()); - } - - public MethodBodyStatement(ExtList list) { + public MethodBodyStatement(TypeReference bodySource, + IProgramVariable resultVar, + MethodReference methodReference) { + this(null, null, resultVar, bodySource, methodReference, null); + assert methodReference != null : "Missing methodreference"; + assert methodReference.getReferencePrefix() != null : + "Method reference of a method body statement needs an " + + "explicit reference prefix."; + checkOnlyProgramVarsAsArguments(methodReference.getArguments()); + } + + public MethodBodyStatement(ExtList list) { + super(list); this.bodySource = list.get(TypeReference.class); - this.resultVar = list.get(IProgramVariable.class); - + this.resultVar = list.get(IProgramVariable.class); + this.methodReference = list.get(MethodReference.class); - + assert methodReference != null : "Missing methodreference"; - assert methodReference.getReferencePrefix() != null : - "Method reference of a method body statement needs an " + - "explicit reference prefix."; + assert methodReference.getReferencePrefix() != null : + "Method reference of a method body statement needs an " + + "explicit reference prefix."; checkOnlyProgramVarsAsArguments(methodReference.getArguments()); - } - - public MethodBodyStatement(IProgramMethod method, - ReferencePrefix newContext, - IProgramVariable res, - ImmutableArray args, - boolean useSpecification){ - this(method, newContext, res, args, useSpecification, null); } - public MethodBodyStatement(IProgramMethod method, - ReferencePrefix newContext, - IProgramVariable res, - ImmutableArray args, - boolean useSpecification, - ProgramElement scope) { + public MethodBodyStatement(IProgramMethod method, ReferencePrefix newContext, + IProgramVariable res, ImmutableArray args) { + this(method, newContext, res, args, null); + } + + public MethodBodyStatement(IProgramMethod method, ReferencePrefix newContext, IProgramVariable res, + ImmutableArray args, ProgramElement scope) { + super((PositionInfo) null, null); this.method = method; - this.bodySource = - new TypeRef(method.getContainerType()); + this.bodySource = new TypeRef(method.getContainerType()); this.resultVar = res; - this.useSpecification = useSpecification; - + if (newContext == null) { if (method.isStatic()) { - newContext = bodySource; + newContext = bodySource; } else { throw new IllegalArgumentException("The invocation target of a method body" + - "statement must be non null"); + "statement must be non null"); } } - + checkOnlyProgramVarsAsArguments(args); - this.methodReference = new MethodReference(args, - method.getProgramElementName(), - newContext); + this.methodReference = new MethodReference(args, + method.getProgramElementName(), + newContext); } - private void checkOnlyProgramVarsAsArguments(ImmutableArray arguments) { - for (int i = 0, sz = arguments.size(); i args) { - this(method, newContext, res, args, false); - } - - public MethodBodyStatement(IProgramMethod method, - ReferencePrefix newContext, - IProgramVariable res, - ImmutableArray args, - ProgramElement scope) { - this(method, newContext, res, args, false, scope); - } - + /** - * Get method body. - * @return the Statement + * Get method body. + * + * @return the Statement */ public Statement getBody(Services services) { - if (method == null) { - resolveMethod(services); + if (method == null) { + resolveMethod(services); } return method.getBody(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { - int i = 0; - if (bodySource != null) i++; + int i = 0; + if (bodySource != null) i++; if (resultVar != null) i++; if (methodReference != null) i++; - return i; + return i; } public ReferencePrefix getDesignatedContext() { return methodReference.getReferencePrefix(); } - + public ImmutableArray getArguments() { return methodReference.getArguments(); } - + /** - * Returns the child at the specified index in this node's "virtual" - * child array. - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array. + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (bodySource != null) { - if (index == 0) { - return bodySource; - } - index--; + if (bodySource != null) { + if (index == 0) { + return bodySource; + } + index--; } - + if (resultVar != null) { if (index == 0) { return resultVar; } index--; } - + if (methodReference != null) { if (index == 0) { return methodReference; - } + } } - - throw new ArrayIndexOutOfBoundsException(); + + throw new ArrayIndexOutOfBoundsException(); } - + public boolean isStatic(Services services) { if (method == null) { resolveMethod(services); @@ -249,31 +226,33 @@ public boolean isStatic(Services services) { } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnMethodBodyStatement(this); + v.performActionOnMethodBodyStatement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - p.printMethodBodyStatement(this); + p.printMethodBodyStatement(this); } - + public IProgramVariable getResultVariable() { - return resultVar; + return resultVar; } - - public KeYJavaType getBodySource() { + + public KeYJavaType getBodySource() { return bodySource.getKeYJavaType(); } - - public TypeReference getBodySourceAsTypeReference() { + + public TypeReference getBodySourceAsTypeReference() { return bodySource; } - - + + public IProgramMethod getProgramMethod(Services services) { if (method == null) { resolveMethod(services); @@ -283,25 +262,20 @@ public IProgramMethod getProgramMethod(Services services) { private void resolveMethod(Services services) { method = services.getJavaInfo(). - getProgramMethod(getBodySource(), - methodReference.getName(), - services.getJavaInfo(). - createSignature(methodReference.getArguments()), - getBodySource()); + getProgramMethod(getBodySource(), + methodReference.getName(), + services.getJavaInfo(). + createSignature(methodReference.getArguments()), + getBodySource()); } public String reuseSignature(Services services, ExecutionContext ec) { - return super.reuseSignature(services, ec)+"("+getBodySource().getName()+")"; + return super.reuseSignature(services, ec) + "(" + getBodySource().getName() + ")"; } - - + public MethodReference getMethodReference() { return methodReference; } - - public boolean replaceBySpecification() { - return useSpecification; - } - + } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodFrame.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodFrame.java index 583807fc8d3..9b41c30f717 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodFrame.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/MethodFrame.java @@ -13,16 +13,7 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.PositionInfo; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.reference.IExecutionContext; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; @@ -30,12 +21,16 @@ import de.uka.ilkd.key.logic.op.IProgramMethod; import de.uka.ilkd.key.logic.op.IProgramVariable; import de.uka.ilkd.key.util.Debug; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * The statement inserted by KeY if a method call is executed. + * The statement inserted by KeY if a method call is executed. */ public class MethodFrame extends JavaStatement implements - Statement, StatementContainer, ProgramPrefix { + Statement, StatementContainer, ProgramPrefix { /** * result @@ -43,76 +38,88 @@ public class MethodFrame extends JavaStatement implements private final IProgramVariable resultVar; /** - * Body. + * Body. */ + @Nonnull private final StatementBlock body; - + private final IExecutionContext execContext; - + private final PosInProgram firstActiveChildPos; private final int prefixLength; private final MethodFrame innerMostMethodFrame; - - - + + + public MethodFrame(PositionInfo pos, List comments, IProgramVariable resultVar, + @Nonnull StatementBlock body, + IExecutionContext execContext, PosInProgram firstActiveChildPos, + int prefixLength, MethodFrame innerMostMethodFrame) { + super(pos, comments); + this.resultVar = resultVar; + this.body = body; + this.execContext = execContext; + this.firstActiveChildPos = firstActiveChildPos; + this.prefixLength = prefixLength; + this.innerMostMethodFrame = innerMostMethodFrame; + } + /** - * Labeled statement. - * @param resultVar the ProgramVariable the return value is assigned to - * @param body a Statement containing the method body of - * the called method + * Labeled statement. + * + * @param resultVar the ProgramVariable the return value is assigned to + * @param body a Statement containing the method body of + * the called method */ - public MethodFrame(IProgramVariable resultVar, - IExecutionContext execContext, - StatementBlock body) { - this.resultVar = resultVar; - this.body = body; + public MethodFrame(IProgramVariable resultVar, IExecutionContext execContext, StatementBlock body) { + super((PositionInfo) null, null); + this.resultVar = resultVar; + this.body = body; this.execContext = execContext; - - firstActiveChildPos = + + firstActiveChildPos = body.isEmpty() ? PosInProgram.TOP : PosInProgram.TOP. - down(getChildCount()-1).down(0); + down(getChildCount() - 1).down(0); - Debug.assertTrue(execContext != null, - "methodframe: executioncontext missing"); - Debug.assertTrue(body != null, - "methodframe: body missing"); - - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); - prefixLength = info.getLength(); - innerMostMethodFrame = info.getInnerMostMethodFrame(); + Debug.assertTrue(execContext != null, "methodframe: executioncontext missing"); + Debug.assertTrue(true, "methodframe: body missing"); + + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + prefixLength = info.getLength(); + innerMostMethodFrame = info.getInnerMostMethodFrame(); } - + /** - * Labeled statement. - * @param resultVar the ProgramVariable the return value is assigned to - * @param body a Statement containing the method body of - * the called method + * Labeled statement. + * + * @param resultVar the ProgramVariable the return value is assigned to + * @param body a Statement containing the method body of + * the called method */ - public MethodFrame(IProgramVariable resultVar, - IExecutionContext execContext, - StatementBlock body, + public MethodFrame(IProgramVariable resultVar, + IExecutionContext execContext, + StatementBlock body, PositionInfo pos) { super(pos); - this.resultVar = resultVar; - this.body = body; + this.resultVar = resultVar; + this.body = body; this.execContext = execContext; - - firstActiveChildPos = + + firstActiveChildPos = body.isEmpty() ? PosInProgram.TOP : PosInProgram.TOP. - down(getChildCount()-1).down(0); - - - Debug.assertTrue(execContext != null, - "methodframe: executioncontext missing"); - Debug.assertTrue(body != null, - "methodframe: body missing"); - - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); - prefixLength = info.getLength(); - innerMostMethodFrame = info.getInnerMostMethodFrame(); + down(getChildCount() - 1).down(0); + + + Debug.assertTrue(execContext != null, + "methodframe: executioncontext missing"); + Debug.assertTrue(true, + "methodframe: body missing"); + + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + prefixLength = info.getLength(); + innerMostMethodFrame = info.getInnerMostMethodFrame(); } @@ -129,13 +136,13 @@ public ProgramPrefix getNextPrefixElement() { throw new IndexOutOfBoundsException("No next prefix element " + this); } } - + @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : - this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : + this; } - + @Override public int getPrefixLength() { return prefixLength; @@ -149,12 +156,13 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } - - public PosInProgram getFirstActiveChildPos() { + } + + public PosInProgram getFirstActiveChildPos() { return firstActiveChildPos; } - + + @Nonnull public SourceElement getFirstElement() { // return getChildAt(0).getFirstElement(); -VK return body.getFirstElement(); @@ -165,16 +173,18 @@ public SourceElement getFirstElementIncludingBlocks() { return body; } - public SourceElement getLastElement() { + @Nonnull + public SourceElement getLastElement() { return body.getLastElement(); } /** - * Get the method call header. - * @return the MethodCallHeader + * Get the method call header. + * + * @return the MethodCallHeader */ public IProgramVariable getProgramVariable() { - return resultVar; + return resultVar; } /** @@ -182,48 +192,52 @@ public IProgramVariable getProgramVariable() { * frame's body */ public IExecutionContext getExecutionContext() { - return execContext; + return execContext; } /** - * Get body. - * @return the Statement + * Get body. + * + * @return the Statement */ + @Nonnull public StatementBlock getBody() { return body; } - - + + /** - * Get method. - * @return the method + * Get method. + * + * @return the method */ public IProgramMethod getProgramMethod() { return getExecutionContext().getMethodContext(); } - /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { int result = 0; if (resultVar != null) result++; if (execContext != null) result++; - if (body != null) result++; + result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { @@ -235,47 +249,49 @@ public ProgramElement getChildAt(int index) { if (index == 0) return execContext; index--; } - if (body != null) { - if (index == 0) return body; - index--; - } + if (index == 0) return body; + index--; throw new ArrayIndexOutOfBoundsException(); } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { - return (body != null) ? 1 : 0; + return 1; } /** - * Return the statement at the specified index in this node's - * "virtual" statement array. - * @param index an index for a statement. - * @return the statement with the given index. - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds. + * Return the statement at the specified index in this node's + * "virtual" statement array. + * + * @param index an index for a statement. + * @return the statement with the given index. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. */ public Statement getStatementAt(int index) { - if (body != null && index == 0) { + if (index == 0) { return body; } throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnMethodFrame(this); + v.performActionOnMethodFrame(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - p.printMethodFrame(this); + p.printMethodFrame(this); } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Return.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Return.java index a9216391519..5b34ca48a08 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Return.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Return.java @@ -12,44 +12,51 @@ // package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; -/** - * Return. - * - */ +import org.key_project.util.ExtList; -public class Return extends ExpressionJumpStatement { +import javax.annotation.Nonnull; +import java.util.List; +public class Return extends ExpressionJumpStatement { + public Return(PositionInfo pi, List comments, @Nonnull Expression expression) { + super(pi, comments, expression); + } /** * Expression jump statement. - * @param expr an Expression used to jump + * + * @param expr an Expression used to jump */ - public Return(Expression expr) { - super(expr); + public Return(@Nonnull Expression expr) { + super(expr); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * May contain: an Expression (as expression of the - * ExpressionJumpStatement), - * Comments - */ + * May contain: an Expression (as expression of the + * ExpressionJumpStatement), + * Comments + */ public Return(ExtList children) { - super(children); + super(children); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnReturn(this); + v.performActionOnReturn(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Switch.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Switch.java index 31c71adb5ad..52a5f6202a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Switch.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Switch.java @@ -13,101 +13,68 @@ package de.uka.ilkd.key.java.statement; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.visitor.Visitor; import org.key_project.util.ExtList; import org.key_project.util.collection.ImmutableArray; -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.TypeScope; -import de.uka.ilkd.key.java.VariableScope; -import de.uka.ilkd.key.java.visitor.Visitor; - -/** - * Switch. - */ - -public class Switch extends BranchStatement - implements ExpressionContainer, - VariableScope, TypeScope { - - /** - * Branches. - */ - - protected final ImmutableArray branches; - - /** - * Expression. - */ +import java.util.List; - protected final Expression expression; +public final class Switch extends BranchStatement implements ExpressionContainer, VariableScope, TypeScope { + private final Expression expression; + private final ImmutableArray branches; - - - /** - * Switch. - */ - - public Switch() { - this.branches=null; - this.expression=null; - } - - /** - * Switch. - * @param e an expression. - */ - - public Switch(Expression e) { - this.branches=null; - this.expression=e; + public Switch(PositionInfo pi, List comments, Expression expression, ImmutableArray branches) { + super(pi, comments); + this.branches = branches; + this.expression = expression; } /** - * Switch. - * @param e an expression. - * @param branches a branch array + * Switch. + * + * @param e an expression. + * @param branches a branch array */ - public Switch(Expression e, Branch[] branches) { - this.branches=new ImmutableArray(branches); - this.expression=e; + this(null, null, e, new ImmutableArray<>(branches)); } /** - * Switch. - * @param children a list with all children + * Switch. + * + * @param children a list with all children */ public Switch(ExtList children) { super(children); - this.expression = children.get(Expression.class); - this.branches=new ImmutableArray(children.collect(Branch.class)); + this.expression = children.get(Expression.class); + this.branches = new ImmutableArray<>(children.collect(Branch.class)); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; if (expression != null) result++; - if (branches != null) result += branches.size(); + if (branches != null) result += branches.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ public ProgramElement getChildAt(int index) { if (expression != null) { @@ -121,8 +88,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { @@ -146,8 +114,9 @@ public Expression getExpressionAt(int index) { } /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { @@ -156,8 +125,9 @@ public Expression getExpression() { /** - * Get the number of branches in this container. - * @return the number of branches. + * Get the number of branches in this container. + * + * @return the number of branches. */ public int getBranchCount() { @@ -185,15 +155,17 @@ public Branch getBranchAt(int index) { * @return the array wrapper of the branches */ public ImmutableArray getBranchList() { - return branches; + return branches; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnSwitch(this); + v.performActionOnSwitch(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/SynchronizedBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/SynchronizedBlock.java index 002220b9a63..98f0c80f433 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/SynchronizedBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/SynchronizedBlock.java @@ -13,74 +13,67 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.ExpressionContainer; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.MetaClassReference; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramPrefix; import de.uka.ilkd.key.logic.op.ProgramVariable; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Synchronized block. + * Synchronized block. */ -public class SynchronizedBlock extends JavaStatement - implements StatementContainer, ExpressionContainer, ProgramPrefix { - - /** - * Expression. - */ - - protected final Expression expression; - - /** - * Body. - */ - - protected final StatementBlock body; +public final class SynchronizedBlock extends JavaStatement + implements StatementContainer, ExpressionContainer, ProgramPrefix { + private final Expression expression; + private final StatementBlock body; private final MethodFrame innerMostMethodFrame; - private final int prefixLength; - - - + + public SynchronizedBlock(PositionInfo pi, List comments, Expression expression, StatementBlock body, + MethodFrame innerMostMethodFrame, int prefixLength) { + super(pi, comments); + this.expression = expression; + this.body = body; + this.innerMostMethodFrame = innerMostMethodFrame; + this.prefixLength = prefixLength; + } + /** - * Synchronized block. - * @param body a statement block. + * Synchronized block. + * + * @param body a statement block. */ public SynchronizedBlock(StatementBlock body) { - this.body=body; - this.expression=null; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); - prefixLength = info.getLength(); - innerMostMethodFrame = info.getInnerMostMethodFrame(); + super((PositionInfo) null, null); + this.body = body; + this.expression = null; + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + prefixLength = info.getLength(); + innerMostMethodFrame = info.getInnerMostMethodFrame(); } /** - * Synchronized block. - * @param e an expression. - * @param body a statement block. + * Synchronized block. + * + * @param e an expression. + * @param body a statement block. */ public SynchronizedBlock(Expression e, StatementBlock body) { - expression=e; - this.body=body; + super((PositionInfo) null, null); + expression = e; + this.body = body; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -88,17 +81,18 @@ public SynchronizedBlock(Expression e, StatementBlock body) { } /** - * Synchronized block. - * @param children a list with all children + * Synchronized block. + * + * @param children a list with all children */ public SynchronizedBlock(ExtList children) { super(children); - expression = children.get(Expression.class); - body = children.get(StatementBlock.class); - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); - prefixLength = info.getLength(); - innerMostMethodFrame = info.getInnerMostMethodFrame(); + expression = children.get(Expression.class); + body = children.get(StatementBlock.class); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + prefixLength = info.getLength(); + innerMostMethodFrame = info.getInnerMostMethodFrame(); } @@ -115,13 +109,13 @@ public ProgramPrefix getNextPrefixElement() { throw new IndexOutOfBoundsException("No next prefix element " + this); } } - + @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : - this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : + this; } - + @Override public int getPrefixLength() { return prefixLength; @@ -135,7 +129,7 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } + } /** * The method checks whether the expression in the synchronized @@ -143,23 +137,25 @@ public ImmutableArray getPrefixElements() { * (as local variables of this type are not supported by KeY, * see return value for * {@link MetaClassReference#getKeYJavaType(Services, ExecutionContext)}. + * * @return true iff the above stated condition holds. */ private boolean expressionWithoutSideffects() { return (expression instanceof ProgramVariable - && !((ProgramVariable)expression).isMember()) + && !((ProgramVariable) expression).isMember()) || (expression instanceof MetaClassReference); } public PosInProgram getFirstActiveChildPos() { return getStatementCount() == 0 ? PosInProgram.TOP : (expressionWithoutSideffects() ? - PosInProgram.TOP.down(getChildCount()-1).down(0) : PosInProgram.ONE); + PosInProgram.TOP.down(getChildCount() - 1).down(0) : PosInProgram.ONE); } - + /** - * Get the number of expressions in this container. - * @return the number of expressions. + * Get the number of expressions in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { @@ -184,8 +180,9 @@ public Expression getExpressionAt(int index) { /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { @@ -193,27 +190,29 @@ public Expression getExpression() { } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; if (expression != null) result++; - if (body != null) result++; + if (body != null) result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ - public ProgramElement getChildAt(int index) { + public ProgramElement getChildAt(int index) { if (expression != null) { if (index == 0) return expression; index--; @@ -225,8 +224,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get body. - * @return the statement block. + * Get body. + * + * @return the statement block. */ public StatementBlock getBody() { @@ -235,8 +235,9 @@ public StatementBlock getBody() { /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { @@ -258,20 +259,22 @@ public Statement getStatementAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } - + @Nonnull public SourceElement getFirstElement() { return body.getFirstElement(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnSynchronizedBlock(this); + v.performActionOnSynchronizedBlock(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Then.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Then.java index 869b3105221..86f97c373a6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Then.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Then.java @@ -12,46 +12,49 @@ // package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import javax.annotation.Nonnull; +import java.util.List; /** - * Then. - * @author AutoDoc + * Then. + * + * @author AutoDoc */ -public class Then extends BranchImp { - - /** - * Body. - */ - - protected Statement body; +public final class Then extends BranchImp { + private final Statement body; + public Then(PositionInfo pi, List comments, Statement body) { + super(pi, comments); + this.body = body; + } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - */ + */ public Then(ExtList children) { - super(children); - body=children.get(Statement.class); + super(children); + body = children.get(Statement.class); } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param stmnt the statement part of Then. - */ - public Then(Statement stmnt) { - this.body=stmnt; + */ + public Then(@Nonnull Statement stmnt) { + this(null, null, stmnt); } + @Nonnull public SourceElement getFirstElement() { return body.getFirstElement(); } @@ -61,14 +64,16 @@ public SourceElement getFirstElementIncludingBlocks() { return body.getFirstElementIncludingBlocks(); } + @Nonnull public SourceElement getLastElement() { return body.getLastElement(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node */ public int getChildCount() { @@ -78,10 +83,11 @@ public int getChildCount() { /** * Returns the child at the specified index in this node's "virtual" * child array + * * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { @@ -92,8 +98,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { @@ -117,19 +124,21 @@ public Statement getStatementAt(int index) { } /** - * The body may be empty (null), to define a fall-through. - * Attaching an {@link EmptyStatement} would create a single ";". + * The body may be empty (null), to define a fall-through. + * Attaching an {@link EmptyStatement} would create a single ";". */ public Statement getBody() { return body; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnThen(this); + v.performActionOnThen(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Throw.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Throw.java index e1287dfb349..f5ea6baee7c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Throw.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Throw.java @@ -13,28 +13,23 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; - +import de.uka.ilkd.key.java.Comment; import de.uka.ilkd.key.java.Expression; +import de.uka.ilkd.key.java.PositionInfo; import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; +import org.key_project.util.ExtList; + +import java.util.List; /** - * Throw. + * Throw. */ public class Throw extends ExpressionJumpStatement { - - /** - * Throw. - */ - - public Throw() {} - - /** - * Throw. - * @param expr an expression. - */ + public Throw(PositionInfo pi, List comments, Expression expression) { + super(pi, comments, expression); + } public Throw(Expression expr) { super(expr); @@ -44,20 +39,23 @@ public Throw(Expression expr) { } /** - * Throw. - * @param children an ExtList with all children + * Throw. + * + * @param children an ExtList with all children */ public Throw(ExtList children) { super(children); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnThrow(this); + v.performActionOnThrow(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/TransactionStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/TransactionStatement.java index 07d6ff9fb86..eda932c9c4b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/TransactionStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/TransactionStatement.java @@ -13,28 +13,33 @@ package de.uka.ilkd.key.java.statement; -import de.uka.ilkd.key.java.NameAbstractionTable; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.SourceData; -import de.uka.ilkd.key.java.SourceElement; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.rule.MatchConditions; -public class TransactionStatement extends JavaStatement { +import java.util.List; - public static final String[] names = { - "#beginJavaCardTransaction", "#commitJavaCardTransaction", "#finishJavaCardTransaction", "#abortJavaCardTransaction" - }; +public final class TransactionStatement extends JavaStatement { + public static final String[] names = { + "#beginJavaCardTransaction", "#commitJavaCardTransaction", + "#finishJavaCardTransaction", "#abortJavaCardTransaction" + }; - private int type; - - public TransactionStatement(int type) { - super(); - if(type != de.uka.ilkd.key.java.recoderext.TransactionStatement.BEGIN && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.COMMIT - && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.FINISH && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.ABORT) { - throw new IllegalArgumentException("Wrong transaction statement type "+type); - } + private final int type; + + public TransactionStatement(PositionInfo pi, List comments, int type) { + super(pi, comments); this.type = type; + if (type != de.uka.ilkd.key.java.recoderext.TransactionStatement.BEGIN + && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.COMMIT + && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.FINISH + && type != de.uka.ilkd.key.java.recoderext.TransactionStatement.ABORT) { + throw new IllegalArgumentException("Wrong transaction statement type " + type); + } + } + + public TransactionStatement(int type) { + this(null, null, type); } @Override @@ -55,31 +60,31 @@ public int getChildCount() { public void prettyPrint(de.uka.ilkd.key.java.PrettyPrinter p) throws java.io.IOException { p.printTransactionStatement(this); } - + public int getPrecedence() { return 13; } - + public String toString() { return names[type - 1]; } - + public boolean equals(Object o) { if (o != null && o instanceof TransactionStatement) { - return ((TransactionStatement)o).type == this.type; + return ((TransactionStatement) o).type == this.type; } return false; } public MatchConditions match(SourceData source, MatchConditions conditions) { - if(this.equals(source.getSource())) { + if (this.equals(source.getSource())) { source.next(); return conditions; } return null; } - + public boolean equalsModRenaming(SourceElement source, NameAbstractionTable nat) { return this.equals(source); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Try.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Try.java index bd94b15396b..7bd9a803a56 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Try.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Try.java @@ -13,65 +13,52 @@ package de.uka.ilkd.key.java.statement; -import org.key_project.util.ExtList; -import org.key_project.util.collection.ImmutableArray; - -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.ProgramPrefixUtil; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementBlock; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.PosInProgram; import de.uka.ilkd.key.logic.ProgramPrefix; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** - * Try. - * @author AutoDoc - */ -public class Try extends BranchStatement - implements StatementContainer, ProgramPrefix { - - /** - * Body. - */ +import javax.annotation.Nonnull; +import java.util.List; - private final StatementBlock body; - - /** - * Branches. - */ +public class Try extends BranchStatement implements StatementContainer, ProgramPrefix { + private final StatementBlock body; private final ImmutableArray branches; - private final MethodFrame innerMostMethodFrame; - private final int prefixLength; - - /** - * Try. - * @param body a statement block. - */ + + public Try(PositionInfo pi, List comments, StatementBlock body, ImmutableArray branches, + MethodFrame innerMostMethodFrame, int prefixLength) { + super(pi, comments); + this.body = body; + this.branches = branches; + this.innerMostMethodFrame = innerMostMethodFrame; + this.prefixLength = prefixLength; + } public Try(StatementBlock body) { - this.body = body; - this.branches = null; + super(null, null); + this.body = body; + this.branches = null; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); } /** - * Try. - * @param body a statement block. - * @param branches a branch array. + * Try. + * + * @param body a statement block. + * @param branches a branch array. */ public Try(StatementBlock body, Branch[] branches) { - this.body = body; - this.branches = new ImmutableArray(branches); + super(null, null); + this.body = body; + this.branches = new ImmutableArray(branches); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -79,29 +66,31 @@ public Try(StatementBlock body, Branch[] branches) { } /** - * Try. - * @param body a statement block. - * @param branches a branch array. + * Try. + * + * @param body a statement block. + * @param branches a branch array. */ public Try(StatementBlock body, ImmutableArray branches) { - this.body=body; + super(null, null); + this.body = body; this.branches = branches; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); - } /** - * Try. - * @param children a list with all children + * Try. + * + * @param children a list with all children */ public Try(ExtList children) { super(children); this.body = children.get(StatementBlock.class); - this.branches=new + this.branches = new ImmutableArray(children.collect(Branch.class)); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); @@ -122,13 +111,13 @@ public ProgramPrefix getNextPrefixElement() { throw new IndexOutOfBoundsException("No next prefix element " + this); } } - + @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : - this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : + this; } - + @Override public int getPrefixLength() { return prefixLength; @@ -142,38 +131,42 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } + } + - + @Nonnull public SourceElement getFirstElement() { return body.getFirstElement(); } + @Nonnull public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } /** - * Returns the number of children of this node. - * @return an int giving the number of children of this node - */ + * Returns the number of children of this node. + * + * @return an int giving the number of children of this node + */ public int getChildCount() { int result = 0; - if (body != null) result++; + if (body != null) result++; if (branches != null) result += branches.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array - * @param index an index into this node's "virtual" child array - * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds - */ + * Returns the child at the specified index in this node's "virtual" + * child array + * + * @param index an index into this node's "virtual" child array + * @return the program element at the given position + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds + */ public ProgramElement getChildAt(int index) { if (body != null) { @@ -187,8 +180,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get body. - * @return the statement block. + * Get body. + * + * @return the statement block. */ public StatementBlock getBody() { @@ -196,8 +190,9 @@ public StatementBlock getBody() { } /** - * Get the number of statements in this container. - * @return the number of statements. + * Get the number of statements in this container. + * + * @return the number of statements. */ public int getStatementCount() { @@ -221,8 +216,9 @@ public Statement getStatementAt(int index) { } /** - * Get the number of branches in this container. - * @return the number of branches. + * Get the number of branches in this container. + * + * @return the number of branches. */ public int getBranchCount() { @@ -230,13 +226,14 @@ public int getBranchCount() { } /** - Return the branch at the specified index in this node's - "virtual" branch array. - @param index an index for a branch. - @return the branch with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the branch at the specified index in this node's + * "virtual" branch array. + * + * @param index an index for a branch. + * @return the branch with the given index. + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds. + */ public Branch getBranchAt(int index) { if (branches != null) { @@ -245,19 +242,23 @@ public Branch getBranchAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** Return the branch array wrapper + /** + * Return the branch array wrapper + * * @return the array wrapper of the branches */ public ImmutableArray getBranchList() { - return branches; + return branches; } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnTry(this); + v.performActionOnTry(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -265,6 +266,6 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public PosInProgram getFirstActiveChildPos() { - return body.isEmpty() ? PosInProgram.TOP : PosInProgram.ZERO_ZERO; + return body.isEmpty() ? PosInProgram.TOP : PosInProgram.ZERO_ZERO; } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/While.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/While.java index 28d1698931a..e80d58d3897 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/While.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/While.java @@ -22,6 +22,8 @@ import de.uka.ilkd.key.java.Statement; import de.uka.ilkd.key.java.visitor.Visitor; +import javax.annotation.Nonnull; + /** * While. */ @@ -67,6 +69,7 @@ public While(Expression guard, Statement body, PositionInfo pos){ super(guard, body, pos); } + @Nonnull public SourceElement getLastElement() { return (body != null) ? body.getLastElement() : this; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserUtil.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserUtil.java index 119bccd2780..c23a8f9b3d0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserUtil.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserUtil.java @@ -22,7 +22,7 @@ public static void checkValidSingletonReference(Expression expr, Token tok) { //weigl: I hope I catch them all. if (expr instanceof VariableReference || expr instanceof ThisReference - || expr instanceof ArrayReference + //|| expr instanceof ArrayReference || expr instanceof ArrayLengthReference || expr instanceof UncollatedReferenceQualifier || expr instanceof SuperReference) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/rule/metaconstruct/ProgramTransformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/rule/metaconstruct/ProgramTransformer.java index 7b47834d302..bcf63a633d2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/rule/metaconstruct/ProgramTransformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/rule/metaconstruct/ProgramTransformer.java @@ -13,19 +13,7 @@ package de.uka.ilkd.key.rule.metaconstruct; -import java.io.IOException; - -import org.key_project.util.collection.ImmutableList; -import org.key_project.util.collection.ImmutableSLList; - -import de.uka.ilkd.key.java.Expression; -import de.uka.ilkd.key.java.JavaNonTerminalProgramElement; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.java.SourceElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.StatementContainer; +import de.uka.ilkd.key.java.*; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.PackageReference; @@ -37,12 +25,18 @@ import de.uka.ilkd.key.logic.TermServices; import de.uka.ilkd.key.logic.op.SchemaVariable; import de.uka.ilkd.key.rule.inst.SVInstantiations; +import org.key_project.util.collection.ImmutableList; +import org.key_project.util.collection.ImmutableSLList; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.List; -/** - * ProgramTransformers are used to describe schematic transformations +/** + * ProgramTransformers are used to describe schematic transformations * that cannot be expressed by the taclet language itself. For * example: - *

    + *
      *
    1. transformations needing access to the java (type) model, e.g * dynamic dispatch of program methods
    2. *
    3. complex transformations that are hard (or not) to express via @@ -54,70 +48,92 @@ * taclets. */ public abstract class ProgramTransformer extends JavaNonTerminalProgramElement - implements StatementContainer, Statement, Expression, TypeReference { + implements StatementContainer, Statement, Expression, TypeReference { - /** the name of the meta construct */ - private Name name; - /** the encapsulated program element */ - private ProgramElement body; + /** + * the name of the meta construct + */ + private final Name name; + /** + * the encapsulated program element + */ + private final ProgramElement body; - /** creates a ProgramTransformer - * @param name the Name of the meta construct - * @param body the ProgramElement contained by the meta construct + public ProgramTransformer(PositionInfo pi, List comments, Name name, ProgramElement body) { + super(pi, comments); + this.name = name; + this.body = body; + } + + /** + * creates a ProgramTransformer + * + * @param name the Name of the meta construct + * @param body the ProgramElement contained by the meta construct */ public ProgramTransformer(Name name, ProgramElement body) { - this.name = name; - this.body = body; + this(null, null, name, body); } - /** creates a ProgramTransformer + /** + * creates a ProgramTransformer + * * @param name the String with the name of the meta construct - * @param body the ProgramElement contained by the meta construct + * @param body the ProgramElement contained by the meta construct */ public ProgramTransformer(String name, ProgramElement body) { - this(new Name(name), body); + this(new Name(name), body); } - /** performs the program transformation needed for symbolic - * program transformation - * @param pe the ProgramElement on which the execution is performed - * @param services the Services with all necessary information - * about the java programs - * @param svInst the instantiations of the schemavariables + /** + * performs the program transformation needed for symbolic + * program transformation + * + * @param pe the ProgramElement on which the execution is performed + * @param services the Services with all necessary information + * about the java programs + * @param svInst the instantiations of the schemavariables * @return the transformated program */ public abstract ProgramElement[] transform - (ProgramElement pe, Services services, SVInstantiations svInst); - - /** returns the name of the meta construct - * @return the name of the meta construct + (ProgramElement pe, Services services, SVInstantiations svInst); + + /** + * returns the name of the meta construct + * + * @return the name of the meta construct */ public Name name() { - return name; + return name; } - /** returns the body of the meta construct - * @return the body of the meta construct + /** + * returns the body of the meta construct + * + * @return the body of the meta construct */ public ProgramElement body() { - return body; + return body; } /** * Finds the source element that occurs last in the source. + * * @return the last source element in the syntactical representation of * this element, may be equals to this element. - */ + */ + @Nonnull public SourceElement getLastElement() { return (body != null) ? body : this; } /** * Get the number of statements in this container. + * * @return the number of statements. */ public int getStatementCount() { - return (body instanceof Statement ? 1 : 0); + return (body instanceof Statement ? 1 : 0); } @@ -130,134 +146,134 @@ public int getStatementCount() { * of bounds. */ public Statement getStatementAt(int index) { - if (index == 0 && body instanceof Statement) { - return (Statement)body; - } else if (!(body instanceof Statement)) { - return null; - } else { - throw new ArrayIndexOutOfBoundsException - ("A ProgramTransformer contains only one statement "); - } + if (index == 0 && body instanceof Statement) { + return (Statement) body; + } else if (!(body instanceof Statement)) { + return null; + } else { + throw new ArrayIndexOutOfBoundsException + ("A ProgramTransformer contains only one statement "); + } } /** * Returns the number of children of this node. + * * @return an int giving the number of children of this node */ public int getChildCount() { - return 1; + return 1; } /** * Returns the child at the specified index in this node's "virtual" * child array. + * * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - return body; + return body; } - + //-------------some methods to pretend being a type reference -------- public ReferencePrefix getReferencePrefix() { - return null; - } - - public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return null; } - public int getDimensions() { - return 0; + return 0; } - public int getTypeReferenceCount(){ - return 0; + public int getTypeReferenceCount() { + return 0; } public TypeReference getTypeReferenceAt(int index) { - return this; + return this; } public PackageReference getPackageReference() { - return null; + return null; } public int getExpressionCount() { - return 0; + return 0; } public Expression getExpressionAt(int index) { - return null; + return null; } public ProgramElementName getProgramElementName() { - return new ProgramElementName(toString()); - } + return new ProgramElementName(toString()); + } public String getName() { - return toString(); + return toString(); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnProgramMetaConstruct(this); + v.performActionOnProgramMetaConstruct(this); } public void prettyPrint(PrettyPrinter p) throws IOException { p.printProgramMetaConstruct(this); } - /** to String */ + /** + * to String + */ public String toString() { - return name+"( "+body+ ");"; + return name + "( " + body + ");"; } public KeYJavaType getKeYJavaType() { - return null; + return null; } + //TODO weigl please revise public KeYJavaType getKeYJavaType(TermServices javaServ) { - return getKeYJavaType(); + return getKeYJavaType(); } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return getKeYJavaType(); + return getKeYJavaType(); } - + /** * get a list of schema variables that are needed by this entity when * working given a SV instantiation set. - * - * @param svInst - * the instantiations of SV so far. + * + * @param svInst the instantiations of SV so far. * @return a list of schema variables relevant for this entity; */ public ImmutableList needs() { - return ImmutableSLList.nil(); + return ImmutableSLList.nil(); } - + /** * get a list of schema variables that are needed by this entity when * working given a SV instantiation set. - * - * @param svInst - * the instatiations of SV so far. + * + * @param svInst the instatiations of SV so far. * @return a list of schema variables relevant for this entity; */ public ImmutableList neededInstantiations(SVInstantiations svInst) { - return ImmutableSLList.nil(); + return ImmutableSLList.nil(); } } \ No newline at end of file diff --git a/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java index 4099652c070..0c38466ff58 100644 --- a/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java +++ b/key/key.java/src/main/java/de/uka/ilkd/key/java/JP2KeyConverter.java @@ -12,6 +12,7 @@ import com.github.javaparser.ast.visitor.GenericVisitorAdapter; import com.github.javaparser.ast.visitor.Visitable; import de.uka.ilkd.key.java.declaration.ClassDeclaration; +import de.uka.ilkd.key.java.declaration.FieldSpecification; import de.uka.ilkd.key.java.declaration.InterfaceDeclaration; import de.uka.ilkd.key.java.declaration.modifier.*; import de.uka.ilkd.key.java.expression.ParenthesizedExpression; @@ -24,11 +25,14 @@ import de.uka.ilkd.key.util.parsing.BuildingExceptions; import de.uka.ilkd.key.util.parsing.BuildingIssue; import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; import javax.annotation.Nullable; import java.net.URI; import java.util.Collections; +import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; /** * @author Alexander Weigl @@ -107,98 +111,109 @@ public ModelElement visit(AssertStmt n, Void arg) { @Override public ModelElement visit(AssignExpr n, Void arg) { - var children = visitChildren(n); + var target = (Expression) n.getTarget().accept(this, arg); + var expr = (Expression) n.getValue().accept(this, arg); + var pi = createPositionInfo(n); + var c = createComments(n); switch (n.getOperator()) { case ASSIGN: - return new CopyAssignment(children); + return new CopyAssignment(pi, c, target, expr); case PLUS: - return new PlusAssignment(children); + return new PlusAssignment(pi, c, target, expr); case MINUS: - return new MinusAssignment(children); + return new MinusAssignment(pi, c, target, expr); case MULTIPLY: - return new TimesAssignment(children); + return new TimesAssignment(pi, c, target, expr); case DIVIDE: - return new DivideAssignment(children); + return new DivideAssignment(pi, c, target, expr); case BINARY_AND: - return new BinaryAndAssignment(children); + return new BinaryAndAssignment(pi, c, target, expr); case BINARY_OR: - return new BinaryOrAssignment(children); + return new BinaryOrAssignment(pi, c, target, expr); case XOR: - return new BinaryXOrAssignment(children); + return new BinaryXOrAssignment(pi, c, target, expr); case REMAINDER: - return new ModuloAssignment(children); + return new ModuloAssignment(pi, c, target, expr); case LEFT_SHIFT: - return new ShiftLeftAssignment(children); + return new ShiftLeftAssignment(pi, c, target, expr); case SIGNED_RIGHT_SHIFT: - return new UnsignedShiftRightAssignment(children); + return new UnsignedShiftRightAssignment(pi, c, target, expr); case UNSIGNED_RIGHT_SHIFT: - return new ShiftRightAssignment(children); + return new ShiftRightAssignment(pi, c, target, expr); } return null; } @Override public ModelElement visit(BinaryExpr n, Void arg) { - var children = visitChildren(n); + var lhs = (Expression) n.getLeft().accept(this, arg); + var rhs = (Expression) n.getRight().accept(this, arg); + var pi = createPositionInfo(n); + var c = createComments(n); switch (n.getOperator()) { case OR: - return new LogicalOr(children); + return new LogicalOr(pi, c, lhs, rhs); case AND: - return new LogicalAnd(children); + return new LogicalAnd(pi, c, lhs, rhs); case BINARY_OR: - return new BinaryOr(children); + return new BinaryOr(pi, c, lhs, rhs); case BINARY_AND: - return new BinaryAnd(children); + return new BinaryAnd(pi, c, lhs, rhs); case XOR: - return new BinaryXOr(children); + return new BinaryXOr(pi, c, lhs, rhs); case EQUALS: - return new Equals(children); + return new Equals(pi, c, lhs, rhs); case NOT_EQUALS: - return new NotEquals(children); + return new NotEquals(pi, c, lhs, rhs); case LESS: - return new LessThan(children); + return new LessThan(pi, c, lhs, rhs); case GREATER: - return new GreaterThan(children); + return new GreaterThan(pi, c, lhs, rhs); case LESS_EQUALS: - return new LessOrEquals(children); + return new LessOrEquals(pi, c, lhs, rhs); case GREATER_EQUALS: - return new GreaterOrEquals(children); + return new GreaterOrEquals(pi, c, lhs, rhs); case LEFT_SHIFT: - return new ShiftLeft(children); + return new ShiftLeft(pi, c, lhs, rhs); case SIGNED_RIGHT_SHIFT: - return new ShiftRight(children); + return new ShiftRight(pi, c, lhs, rhs); case UNSIGNED_RIGHT_SHIFT: - return new UnsignedShiftRight(children); + return new UnsignedShiftRight(pi, c, lhs, rhs); case PLUS: - return new Plus(children); + return new Plus(pi, c, lhs, rhs); case MINUS: - return new Minus(children); + return new Minus(pi, c, lhs, rhs); case MULTIPLY: - return new Times(children); + return new Times(pi, c, lhs, rhs); case DIVIDE: - return new Divide(children); + return new Divide(pi, c, lhs, rhs); case REMAINDER: - return new Modulo(children); + return new Modulo(pi, c, lhs, rhs); } return null; } @Override public ModelElement visit(BlockStmt n, Void arg) { - var children = visitChildren(n); - return new StatementBlock(children); + var body = map(n.getStatements()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new StatementBlock(pi, c, body, 0, null); } @Override public ModelElement visit(BooleanLiteralExpr n, Void arg) { - var children = visitChildren(n); - return new BooleanLiteral(children, n.getValue()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new BooleanLiteral(pi, c, n.getValue()); } @Override public ModelElement visit(BreakStmt n, Void arg) { - var children = visitChildren(n); - return new Break(children); + var pi = createPositionInfo(n); + var c = createComments(n); + var name = n.getLabel(); + return new Break(pi, c, name); } @Override @@ -215,8 +230,9 @@ public ModelElement visit(CatchClause n, Void arg) { @Override public ModelElement visit(CharLiteralExpr n, Void arg) { - var children = visitChildren(n); - return new CharLiteral(children, n.getValue()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new CharLiteral(pi, c, n.getValue().charAt(0)); } @Override @@ -227,7 +243,8 @@ public ModelElement visit(ClassExpr n, Void arg) { @Override public ModelElement visit(ClassOrInterfaceDeclaration n, Void arg) { - var seq = visitChildren(n); + var pi = createPositionInfo(n); + var c = createComments(n); ProgramElementName fullName = new ProgramElementName(n.getNameAsString()); boolean isLibrary = false; //TODO weigl if (n.isInterface()) { @@ -237,7 +254,7 @@ public ModelElement visit(ClassOrInterfaceDeclaration n, Void arg) { } } - private ExtList visitChildren(Node node) { + /*private ExtList visitChildren(Node node) { ExtList seq = new ExtList(node.getChildNodes().size()); for (Node childNode : node.getChildNodes()) { var element = childNode.accept(this, null); @@ -247,13 +264,13 @@ private ExtList visitChildren(Node node) { } seq.add(createPositionInfo(node)); return seq; - } + }*/ - private ModelElement accept(Node check) { + private T accept(Node check) { var a = check.accept(this, null); mapping.put(check, a); - return a; + return (T) a; } private PositionInfo createPositionInfo(Node node) { @@ -277,14 +294,24 @@ public ModelElement visit(ClassOrInterfaceType n, Void arg) { @Override public ModelElement visit(com.github.javaparser.ast.CompilationUnit n, Void arg) { - return new CompilationUnit((PackageSpecification) accepto(n.getPackageDeclaration()), - accepta(n.getImports()), accepta(n.getTypes())); + return new CompilationUnit( + createPositionInfo(n), createComments(n), + (PackageSpecification) accepto(n.getPackageDeclaration()), + map(n.getImports()), + map(n.getTypes())); } - private T[] accepta(NodeList nodes) { - return (T[]) nodes.stream().map(it -> (T) it.accept(this, null)).toArray(); + private List createComments(Node n) { + //TODO weigl + return Collections.emptyList(); } + private ImmutableArray map(NodeList nodes) { + var seq = nodes.stream().map(it -> (T) it.accept(this, null)).collect(Collectors.toList()); + return new ImmutableArray<>(seq); + } + + @Nullable private ModelElement accepto(Optional node) { if (node.isEmpty()) return null; @@ -293,46 +320,65 @@ private ModelElement accepto(Optional node) { @Override public ModelElement visit(ConditionalExpr n, Void arg) { - var children = visitChildren(n); - return new Conditional(children); + var pi = createPositionInfo(n); + var c = createComments(n); + return new Conditional(pi, c, + accept(n.getCondition()), + accept(n.getThenExpr()), + accept(n.getElseExpr())); } @Override public ModelElement visit(ConstructorDeclaration n, Void arg) { boolean parentIsInterface = false; - var children = visitChildren(n); + var pi = createPositionInfo(n); + var c = createComments(n); return new de.uka.ilkd.key.java.declaration.ConstructorDeclaration(children, parentIsInterface); } @Override public ModelElement visit(ContinueStmt n, Void arg) { - var children = visitChildren(n); - return new Continue(children); + var pi = createPositionInfo(n); + var c = createComments(n); + Label name = nameToLabel(n.getLabel()); + return new Continue(pi, c, name); + } + + private Label nameToLabel(Optional label) { + if (label.isPresent()) { + } + return null; } @Override public ModelElement visit(DoStmt n, Void arg) { + var pi = createPositionInfo(n); + var c = createComments(n); var guard = accept(n.getCondition()); var body = accept(n.getBody()); - return new Do((Expression) guard, (Statement) body, createPositionInfo(n)); + return new Do(pi, c, new Guard((Expression) guard), (Statement) body); } @Override public ModelElement visit(DoubleLiteralExpr n, Void arg) { - var children = visitChildren(n); - return new DoubleLiteral(children, n.getValue()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new DoubleLiteral(pi, c, n.getValue()); } @Override public ModelElement visit(EmptyStmt n, Void arg) { - var children = visitChildren(n); - return new EmptyStatement(children); + var pi = createPositionInfo(n); + var c = createComments(n); + return new EmptyStatement(pi, c); } @Override public ModelElement visit(EnclosedExpr n, Void arg) { - var children = visitChildren(n); - return new ParenthesizedExpression(children); + var pi = createPositionInfo(n); + var c = createComments(n); + var expr = accept(n.getInner()); + return new ParenthesizedExpression(pi, c, (Expression) expr); } @Override @@ -354,7 +400,8 @@ public ModelElement visit(ExplicitConstructorInvocationStmt n, Void arg) { @Override public ModelElement visit(ExpressionStmt n, Void arg) { - var seq = visitChildren(n); + var pi = createPositionInfo(n); + var c = createComments(n); return (ModelElement) seq.get(0); } @@ -365,24 +412,41 @@ public ModelElement visit(FieldAccessExpr n, Void arg) { @Override public ModelElement visit(FieldDeclaration n, Void arg) { - var children = visitChildren(n); + var pi = createPositionInfo(n); + var c = createComments(n); boolean parentIsInferface = false; - return new de.uka.ilkd.key.java.declaration.FieldDeclaration(children, parentIsInferface); + var modArray = visitModifiers(n.getModifiers()); + TypeReference type = accept(n.getVariables().get(0).getType()); + ImmutableArray fieldSpecs = n.getVariables(); + return new de.uka.ilkd.key.java.declaration.FieldDeclaration(pi, c, modArray, type, parentIsInferface, fieldSpecs); + } + + private ImmutableArray visitModifiers(NodeList modifiers) { } @Override public ModelElement visit(ForEachStmt n, Void arg) { - return super.visit(n, arg); + var pi = createPositionInfo(n); + var c = createComments(n); + return new EnhancedFor(pi, c, ) } @Override public ModelElement visit(ForStmt n, Void arg) { - return super.visit(n, arg); + var pi = createPositionInfo(n); + var c = createComments(n); + return new EnhancedFor(pi, c, ) } @Override public ModelElement visit(IfStmt n, Void arg) { - return super.visit(n, arg); + var pi = createPositionInfo(n); + var c = createComments(n); + Statement t = (StatementBlock) accept(n.getThenStmt()); + Statement e = (StatementBlock) accepto(n.getElseStmt()); + return new If(pi, c, (Expression) accept(n.getCondition()), + new Then(e), + e != null ? new Else(e) : null); } @Override @@ -392,13 +456,18 @@ public ModelElement visit(InitializerDeclaration n, Void arg) { @Override public ModelElement visit(InstanceOfExpr n, Void arg) { - return super.visit(n, arg); + var pi = createPositionInfo(n); + var c = createComments(n); + var lhs = (Expression) accept(n.getExpression()); + var type = (TypeReference) accept(n.getType()); + return new Instanceof(pi, c, lhs, type); } @Override public ModelElement visit(IntegerLiteralExpr n, Void arg) { - var children = visitChildren(n); - return new IntLiteral(children, n.getValue()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new IntLiteral(pi, c, n.getValue()); } @Override @@ -416,7 +485,9 @@ public ModelElement visit(LabeledStmt n, Void arg) { @Override public ModelElement visit(LongLiteralExpr n, Void arg) { - return new LongLiteral(n.getValue()); + var pi = createPositionInfo(n); + var c = createComments(n); + return new LongLiteral(pi, c, n.getValue()); } @Override @@ -453,7 +524,9 @@ public ModelElement visit(NormalAnnotationExpr n, Void arg) { @Override public ModelElement visit(NullLiteralExpr n, Void arg) { - return NullLiteral.NULL; + var pi = createPositionInfo(n); + var c = createComments(n); + return new NullLiteral(pi, c); } @Override @@ -545,17 +618,25 @@ public ModelElement visit(SwitchEntry n, Void arg) { @Override public ModelElement visit(SwitchStmt n, Void arg) { - return new Switch(visitChildren(n)); + var pi = createPositionInfo(n); + var c = createComments(n); + var expr = null;//TODO + var branches = map(n.getEntries()); + return new Switch(pi, c, expr, branches); } @Override public ModelElement visit(SynchronizedStmt n, Void arg) { - return new Synchronized(visitChildren(n)); + var pi = createPositionInfo(n); + var c = createComments(n); + return new SynchronizedBlock(pi, c, accept(n.getExpression()), accept(n.getBody()), + null, 0); } @Override public ModelElement visit(ThisExpr n, Void arg) { - return new ThisReference(visitChildren(n)); + n.getTypeName();//TODO + return new ThisReference(createPositionInfo(n), createComments(n), null); } @Override diff --git a/key/key.util/src/main/java/org/key_project/util/ExtList.java b/key/key.util/src/main/java/org/key_project/util/ExtList.java index 344b32735b3..c56250271ce 100644 --- a/key/key.util/src/main/java/org/key_project/util/ExtList.java +++ b/key/key.util/src/main/java/org/key_project/util/ExtList.java @@ -14,13 +14,20 @@ package org.key_project.util; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; /** * extends java.util.LinkedList in order to collect elements - * according to their type + * according to their type. + * + * @deprecated This class provides a bad coding style of exploiting reflection in the construction of KeY-Java-AST. + * Will be removed. */ +@Deprecated public class ExtList extends ArrayList { public ExtList() { super(); @@ -61,6 +68,17 @@ public T[] collect(Class cl) { return toArray(cl, colls); } + public List collectList(Class cl) { + List colls = new ArrayList<>(size()); + for (Object next : this) { + if (cl.isInstance(next) && (next != null)) { + colls.add((T) next); + } + } + return colls; + } + + /** * returns first element in list of type cl * From 74401fcab3722acf7a8483592b627e366957b7d0 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 8 Mar 2022 19:35:35 +0100 Subject: [PATCH 008/225] simple expression can be translated, lookup and types are hard --- .../ilkd/key/java/ContextStatementBlock.java | 339 +++--- .../java/declaration/ClassDeclaration.java | 215 ++-- .../ilkd/key/java/declaration/Extends.java | 46 +- .../ilkd/key/java/declaration/Implements.java | 44 +- .../declaration/InterfaceDeclaration.java | 119 +- .../declaration/LocalVariableDeclaration.java | 146 ++- .../declaration/ParameterDeclaration.java | 150 +-- .../key/java/declaration/TypeDeclaration.java | 219 ++-- .../java/declaration/modifier/Private.java | 22 +- .../java/declaration/modifier/Protected.java | 25 +- .../key/java/declaration/modifier/Public.java | 21 +- .../java/expression/PassiveExpression.java | 37 +- .../expression/literal/EmptyMapLiteral.java | 16 +- .../expression/literal/EmptySeqLiteral.java | 26 +- .../expression/literal/EmptySetLiteral.java | 25 +- .../java/expression/literal/FloatLiteral.java | 89 +- .../java/expression/literal/FreeLiteral.java | 12 +- .../java/expression/literal/RealLiteral.java | 85 +- .../expression/literal/StringLiteral.java | 54 +- .../operator/BinaryOrAssignment.java | 12 +- .../operator/DLEmbeddedExpression.java | 76 +- .../java/expression/operator/NewArray.java | 205 ++-- .../java/expression/operator/TypeCast.java | 92 +- .../key/java/recoderext/ExecutionContext.java | 205 ++-- .../ilkd/key/java/statement/EnhancedFor.java | 64 +- .../de/uka/ilkd/key/java/statement/For.java | 69 +- .../de/uka/ilkd/key/java/statement/While.java | 74 +- .../de/uka/ilkd/key/java/JP2KeyConverter.java | 1072 ++++++++++++----- .../de/uka/ilkd/key/java/JavaService.java | 4 +- .../de/uka/ilkd/key/java/KeyJPMapping.java | 14 +- .../src/test/java/TranslationTest.java | 46 + key/key.java/src/test/resources/javaExprs.txt | 26 + .../recoder/java/statement/JavaStatement.java | 9 - 33 files changed, 2131 insertions(+), 1527 deletions(-) create mode 100644 key/key.java/src/test/java/TranslationTest.java create mode 100644 key/key.java/src/test/resources/javaExprs.txt diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ContextStatementBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ContextStatementBlock.java index a8d4a4180d4..3baa9813be5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ContextStatementBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ContextStatementBlock.java @@ -13,10 +13,6 @@ package de.uka.ilkd.key.java; -import java.io.IOException; - -import org.key_project.util.ExtList; - import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.IExecutionContext; import de.uka.ilkd.key.java.statement.MethodFrame; @@ -26,9 +22,15 @@ import de.uka.ilkd.key.logic.ProgramPrefix; import de.uka.ilkd.key.rule.MatchConditions; import de.uka.ilkd.key.rule.inst.SVInstantiations; -import de.uka.ilkd.key.util.Debug; +import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; -/** +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.List; + +/** * In the DL-formulae description of Taclets the program part can have * the following form < pi alpha;...; omega > Phi where pi is a prefix * consisting of open brackets, try's and so on and omega is the rest @@ -38,19 +40,30 @@ */ public class ContextStatementBlock extends StatementBlock { - - - /** - * the last execution context of the context term + /** + * the last execution context of the context term */ + @Nullable private final IExecutionContext executionContext; - /** + /** * length of this progran prefix */ private final int patternPrefixLength; - - /** creates a ContextStatementBlock + + + public ContextStatementBlock(PositionInfo pi, List comments, + @Nonnull ImmutableArray body, + int prefixLength, MethodFrame innerMostMethodFrame, + IExecutionContext executionContext, int patternPrefixLength) { + super(pi, comments, body, prefixLength, innerMostMethodFrame); + this.executionContext = executionContext; + this.patternPrefixLength = patternPrefixLength; + } + + /** + * creates a ContextStatementBlock + * * @param children the body of the context term */ public ContextStatementBlock(ExtList children) { @@ -59,199 +72,197 @@ public ContextStatementBlock(ExtList children) { patternPrefixLength = this.getPrefixLength(); } - /** creates a ContextStatementBlock - * @param children the body of the context term + /** + * creates a ContextStatementBlock + * + * @param children the body of the context term * @param executionContext the required execution context */ - public ContextStatementBlock(ExtList children, - IExecutionContext executionContext) { - super(children); - this.executionContext = executionContext; - patternPrefixLength = this.getPrefixLength(); + public ContextStatementBlock(ExtList children, + IExecutionContext executionContext) { + super(children); + this.executionContext = executionContext; + patternPrefixLength = this.getPrefixLength(); } - public ContextStatementBlock(Statement s, - IExecutionContext executionContext) { + public ContextStatementBlock(Statement s, + IExecutionContext executionContext) { super(s); this.executionContext = executionContext; patternPrefixLength = this.getPrefixLength(); } - - public ContextStatementBlock(Statement[] body, - IExecutionContext executionContext) { + + public ContextStatementBlock(Statement[] body, + IExecutionContext executionContext) { super(body); this.executionContext = executionContext; patternPrefixLength = this.getPrefixLength(); } - public boolean requiresExplicitExecutionContextMatch() { - return executionContext != null; - } - public IExecutionContext getExecutionContext() { - return executionContext; + return executionContext; } /** * Returns the number of children of this node. + * * @return an int giving the number of children of this node - */ + */ public int getChildCount() { - int count = 0; - if (executionContext != null) count++; - count += super.getChildCount(); + int count = 0; + if (executionContext != null) count++; + count += super.getChildCount(); return count; } /** * Returns the child at the specified index in this node's "virtual" * child array + * * @param index an index into this node's "virtual" child array * @return the program element at the given position - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds + * @throws ArrayIndexOutOfBoundsException if index is out + * of bounds */ public ProgramElement getChildAt(int index) { - if (executionContext != null) { - if (index == 0) { - return executionContext; - } - index--; - } - return super.getChildAt(index); + if (executionContext != null) { + if (index == 0) { + return executionContext; + } + index--; + } + return super.getChildAt(index); } - /** calls the corresponding method of a visitor in order to + /** + * calls the corresponding method of a visitor in order to * perform some action/transformation on this element + * * @param v the Visitor */ public void visit(Visitor v) { - v.performActionOnContextStatementBlock(this); + v.performActionOnContextStatementBlock(this); } public void prettyPrint(PrettyPrinter w) throws IOException { - w.printContextStatementBlock(this); + w.printContextStatementBlock(this); } - + /* toString */ public String toString() { - StringBuffer result = new StringBuffer(); - result.append(".."); - result.append(super.toString()); - result.append("\n"); - result.append("..."); - return result.toString(); + return ".." + + super.toString() + + "\n" + + "..."; } - - + public int getTypeDeclarationCount() { - throw new UnsupportedOperationException(getClass()+ - ": We are not quite a StatementBlock"); + throw new UnsupportedOperationException(getClass() + + ": We are not quite a StatementBlock"); } - public de.uka.ilkd.key.java.declaration.TypeDeclaration - getTypeDeclarationAt(int index) { - throw new UnsupportedOperationException(getClass()+ - ": We are not quite a StatementBlock"); + public de.uka.ilkd.key.java.declaration.TypeDeclaration getTypeDeclarationAt(int index) { + throw new UnsupportedOperationException(getClass() + + ": We are not quite a StatementBlock"); } /** - * overrides the check of the superclass as unmatched elements will disappear in + * overrides the check of the superclass as unmatched elements will disappear in * the suffix of this ContextStatementBlock */ public boolean compatibleBlockSize(int pos, int max) { return true; - } - + } + public MatchConditions match(SourceData source, MatchConditions matchCond) { SourceData newSource = source; - + if (matchCond.getInstantiations(). getContextInstantiation() != null) { // Currently we do not allow to context statement block // occurrences in find or assumes clauses return null; } - + final ProgramElement src = newSource.getSource(); - final Services services = source.getServices(); - + final Services services = source.getServices(); + ExecutionContext lastExecutionContext = null; - + final ProgramPrefix prefix; int pos = -1; - PosInProgram relPos = PosInProgram.TOP; - + PosInProgram relPos = PosInProgram.TOP; + if (src instanceof ProgramPrefix) { - prefix = (ProgramPrefix)src; - final int srcPrefixLength = prefix.getPrefixLength(); - + prefix = (ProgramPrefix) src; + final int srcPrefixLength = prefix.getPrefixLength(); + if (patternPrefixLength > srcPrefixLength) { LOGGER.debug("Program match FAILED. Source has not enough prefix elements. This: {} Source: {}", this, source); return null; } - + pos = srcPrefixLength - patternPrefixLength; - - ProgramPrefix firstActiveStatement = getPrefixElementAt(prefix, pos); - + + ProgramPrefix firstActiveStatement = getPrefixElementAt(prefix, pos); + relPos = firstActiveStatement.getFirstActiveChildPos(); - + // firstActiveStatement contains the ProgramPrefix in front of the first active statement // start denotes the child where to start to match // in some cases firstActiveStatement already denotes the element to match // (empty block, empty try block etc.) this is encoded by setting start to -1 int start = -1; - - if (relPos != PosInProgram.TOP) { + + if (relPos != PosInProgram.TOP) { if (firstActiveStatement instanceof MethodFrame) { - lastExecutionContext = (ExecutionContext) - ((MethodFrame)firstActiveStatement). - getExecutionContext(); - } - - start = relPos.get(relPos.depth()-1); - if (relPos.depth()>1) { + lastExecutionContext = (ExecutionContext) + ((MethodFrame) firstActiveStatement). + getExecutionContext(); + } + + start = relPos.get(relPos.depth() - 1); + if (relPos.depth() > 1) { firstActiveStatement = (ProgramPrefix) - PosInProgram.getProgramAt(relPos.up(), - firstActiveStatement); + PosInProgram.getProgramAt(relPos.up(), + firstActiveStatement); } } - newSource = new SourceData(firstActiveStatement, start, services); + newSource = new SourceData(firstActiveStatement, start, services); } else { prefix = null; } - matchCond = matchInnerExecutionContext(matchCond, services, - lastExecutionContext, prefix, pos, src); - + matchCond = matchInnerExecutionContext(matchCond, services, + lastExecutionContext, prefix, pos, src); + if (matchCond == null) { return null; - } - + } + // matching children - matchCond = matchChildren(newSource, matchCond, - executionContext == null ? 0 : 1); - + matchCond = matchChildren(newSource, matchCond, + executionContext == null ? 0 : 1); + if (matchCond == null) { return null; } - + matchCond = makeContextInfoComplete(matchCond, - newSource, - prefix, - pos, - relPos, - src, - services); - + newSource, + prefix, + pos, + relPos, + src, + services); + if (matchCond == null) { return null; - } - + } + LOGGER.debug("Successful match."); return matchCond; } @@ -261,62 +272,63 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { * and the suffix start position */ private MatchConditions makeContextInfoComplete( - MatchConditions matchCond, - SourceData newSource, - ProgramPrefix prefix, - int pos, - PosInProgram relPos, + MatchConditions matchCond, + SourceData newSource, + ProgramPrefix prefix, + int pos, + PosInProgram relPos, ProgramElement src, Services services) { - - final SVInstantiations instantiations = matchCond.getInstantiations(); + + final SVInstantiations instantiations = matchCond.getInstantiations(); final ExecutionContext lastExecutionContext = instantiations.getExecutionContext(); - + final PosInProgram prefixEnd = matchPrefixEnd(prefix, pos, relPos); - + // compute position of the first element not matched - final int lastMatchedPos = newSource.getChildPos(); - final PosInProgram suffixStart = prefixEnd.up().down(lastMatchedPos); - - /** add context block instantiation */ + final int lastMatchedPos = newSource.getChildPos(); + final PosInProgram suffixStart = prefixEnd.up().down(lastMatchedPos); + + /* add context block instantiation */ matchCond = matchCond.setInstantiations - (instantiations.replace(prefixEnd, - suffixStart, - lastExecutionContext, - src, - services)); + (instantiations.replace(prefixEnd, + suffixStart, + lastExecutionContext, + src, + services)); return matchCond; } /** * matches the inner most execution context in prefix, used to resolve references in * succeeding matchings - * @param matchCond the MatchCond the matchonditions already found - * @param services the Services - * @param lastExecutionContext the ExecutionContext if already found - * @param prefix the oute rmost prefixelement of the original source - * @param pos an int as the number of prefix elements to disappear in the context - * @param src the original source + * + * @param matchCond the MatchCond the matchonditions already found + * @param services the Services + * @param lastExecutionContext the ExecutionContext if already found + * @param prefix the oute rmost prefixelement of the original source + * @param pos an int as the number of prefix elements to disappear in the context + * @param src the original source * @return the inner most execution context */ - private MatchConditions matchInnerExecutionContext(MatchConditions matchCond, - final Services services, ExecutionContext lastExecutionContext, - final ProgramPrefix prefix, int pos, final ProgramElement src) { - + private MatchConditions matchInnerExecutionContext(MatchConditions matchCond, + final Services services, ExecutionContext lastExecutionContext, + final ProgramPrefix prefix, int pos, final ProgramElement src) { + // partial context instantiation - + ExecutionContext innerContext = lastExecutionContext; - - if (innerContext == null) { + + if (innerContext == null) { if (prefix != null && prefix.getInnerMostMethodFrame() != null) { innerContext = (ExecutionContext) prefix.getInnerMostMethodFrame().getExecutionContext(); } else { innerContext = services.getJavaInfo().getDefaultExecutionContext(); } } - + if (executionContext != null) { - matchCond = executionContext.match(new SourceData(innerContext, -1, + matchCond = executionContext.match(new SourceData(innerContext, -1, services), matchCond); if (matchCond == null) { LOGGER.debug("Program match. ExecutionContext mismatch."); @@ -324,43 +336,44 @@ private MatchConditions matchInnerExecutionContext(MatchConditions matchCond, } LOGGER.debug("Program match. ExecutionContext matched."); } - - matchCond = - matchCond.setInstantiations(matchCond.getInstantiations(). - add(null, - null, - innerContext, - src, - services)); - + + matchCond = + matchCond.setInstantiations(matchCond.getInstantiations(). + add(null, + null, + innerContext, + src, + services)); + return matchCond; } /** * computes the PosInProgram of the first element, which is not part of the prefix + * * @param prefix the ProgramPrefix the outer most prefix element of the source - * @param pos the number of elements to disappear in the context + * @param pos the number of elements to disappear in the context * @param relPos the position of the first active statement of element - * prefix.getPrefixElementAt(pos); + * prefix.getPrefixElementAt(pos); * @return the PosInProgram of the first element, which is not part of the prefix */ private PosInProgram matchPrefixEnd(final ProgramPrefix prefix, int pos, PosInProgram relPos) { PosInProgram prefixEnd = PosInProgram.TOP; - if (prefix != null) { + if (prefix != null) { ProgramPrefix currentPrefix = prefix; int i = 0; - while (i<=pos) { - final IntIterator it = currentPrefix.getFirstActiveChildPos().iterator(); - while ( it.hasNext() ) { + while (i <= pos) { + final IntIterator it = currentPrefix.getFirstActiveChildPos().iterator(); + while (it.hasNext()) { prefixEnd = prefixEnd.down(it.next()); } i++; - if (i<=pos) { - // as fail-fast measure I do not test here using - // {@link ProgramPrefix#hasNextPrefixElement()} - // It must be guaranteed that there are at least pos + 1 - // prefix elements (incl. prefix) otherwise there - // is a bug already at an earlier point + if (i <= pos) { + // as fail-fast measure I do not test here using + // {@link ProgramPrefix#hasNextPrefixElement()} + // It must be guaranteed that there are at least pos + 1 + // prefix elements (incl. prefix) otherwise there + // is a bug already at an earlier point currentPrefix = currentPrefix.getNextPrefixElement(); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassDeclaration.java index 7964e7a27b9..0b9855b03b1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassDeclaration.java @@ -13,19 +13,20 @@ package de.uka.ilkd.key.java.declaration; +import de.uka.ilkd.key.java.*; +import de.uka.ilkd.key.java.abstraction.KeYJavaType; +import de.uka.ilkd.key.java.visitor.Visitor; +import de.uka.ilkd.key.logic.ProgramElementName; import org.key_project.util.ExtList; +import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; -import de.uka.ilkd.key.java.PrettyPrinter; -import de.uka.ilkd.key.java.ProgramElement; -import de.uka.ilkd.key.java.Statement; -import de.uka.ilkd.key.java.abstraction.KeYJavaType; -import de.uka.ilkd.key.java.visitor.Visitor; -import de.uka.ilkd.key.logic.ProgramElementName; +import javax.annotation.Nonnull; +import java.util.List; /** - * There are several types of class declarations: + * There are several types of class declarations: *